python - 为 python 导出 c++ 函数,传递几个字符串作为参数

标签 python c++

我正在尝试将一些 C++ 函数导出到 python 中,并且它在大多数情况下都运行良好,但是当函数在参数中使用的参数多于字符串时,我遇到了问题,第一个总是可以的,但是其他的总是胡言乱语。

C++代码:

#include <Python.h>

#include <iostream>

PyObject* wrap_one_string(PyObject *self, PyObject *args)
{
    char* str;
    if (!PyArg_ParseTuple(args,"s:wrap_one_string",&str))
    {
        return nullptr;
    }
    std::cout << str << std::endl;
    return Py_None;
}

PyObject* wrap_two_string(PyObject *self, PyObject *args)
{
    char* str1, str2;
    if (!PyArg_ParseTuple(args,"ss:wrap_one_string", &str1, &str2))
    {
        return nullptr;
    }
    std::cout << str1 << std::endl << str2 << std::endl;
    return Py_None;
}

static PyMethodDef exampleMethods[] = {
    { "one_string", wrap_one_string, METH_VARARGS, nullptr },
    { "two_string", wrap_two_string, METH_VARARGS, nullptr },
    { nullptr, nullptr, 0, nullptr}
};

extern "C"
{

    __declspec(dllexport)
    void initexample()
    {
         PyObject *m;
         m = Py_InitModule("example", exampleMethods);
    }

}

python 代码:

import example

example.one_string("ab")
example.two_string("abcd", "efgh")

结果是:

ab
abcd
È

第二个字符串参数总是一个奇怪的字符。 知道这可能来自哪里吗?

谢谢

最佳答案

啊,没关系,我犯了一个愚蠢的错误

char* str1, str2;

应该是

char* str1, *str2;

太糟糕了,它编译了,虽然它确实给出了错误

str2 = PyString_AsString(PyTuple_GET_ITEM(args, 1))

访问第二个字符串。

关于python - 为 python 导出 c++ 函数,传递几个字符串作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32480852/

相关文章:

python - 用于 Win32 平台的 CMake find_package(需要 PythonInterp 3.7)

c++ - 减少(op :var) has the same effect as shared(var)

c++ - Windows 转储文件 (hdmp) - 没有 pdb 文件的信息

c++从不变函数返回时断言失败

python - Django 表单未在生产服务器上呈现 - 使用测试服务器在本地正常工作,并且单元测试在生产服务器上通过

python - 可以在 SQLAlchemy 中设置类似 rails 的关联吗?

python - 如何从没有环境名称的文本文件创建新环境?

c++ - native 数组的 Memcpy 到 C++ CLI 中的托管数组

c++ - Eclipse CDT : cannot debug or terminate application

python - Windows 上没有适用于 Python 3.5 的 cx_Oracle 吗?