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

时间:2015-09-09 13:25:40

标签: 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
È

第二个字符串参数始终是一个奇怪的字符。 知道这可能来自何处?

由于

2 个答案:

答案 0 :(得分:3)

啊,从来没有明白,愚蠢的错误

char* str1, str2;

应该是

char* str1, *str2;

编译太糟糕了,尽管使用

确实出错了
str2 = PyString_AsString(PyTuple_GET_ITEM(args, 1))

访问第二个字符串。

答案 1 :(得分:1)

一个小注释,记得在返回Py_None之前Py_INCREF(Py_None);,如参考文献[https://docs.python.org/2/extending/extending.html#back-to-the-example]中所述 或使用Py_RETURN_NONE宏[https://docs.python.org/2/c-api/none.html#c.Py_RETURN_NONE]