【发布时间】:2017-07-29 11:03:01
【问题描述】:
我试图了解如何在 Python3 和 cythonized C++ 函数之间传递字符串值。但是我无法使用 Cython 构建库。
特别不明白source.pyx中如何声明字符串返回值和字符串参数。使用 int 类型它可以正常工作。
我在使用 clang 构建过程中遇到的错误如下:
candidate function not viable: no known conversion from 'PyObject *' (aka '_object *') to 'char *' for 1st argument
我的source.pyx 如下:
cdef extern from "source.cpp":
cdef str fun(str param)
def pyfun(mystring):
return fun(mystring)
我的source.cpp 是:
char * fun(char *string) {
return string;
}
【问题讨论】:
-
您了解文档的这一部分吗? cython.readthedocs.io/en/latest/src/tutorial/…。我还在努力。
-
谢谢。实际上,我设法在此表 cython.readthedocs.io/en/latest/src/userguide/… 后面传递了字符串。我认为您建议使用
libcpp.string和std::string是否比将bytes传递给char*然后将返回值(类型为bytes)转换为str更好? -
我链接的文档页面似乎对
Cchar 字符串的评价很低,特别是因为Py3 使用unicode。但最好的方法可能取决于您对C++中的字符串所做的操作。 -
事实上,我正在连接旧的遗留代码,而我对 cython 的经验仍然很少。如果您可以使用
libcpp.string作为答案,我可以接受它。
标签: c++ python-3.x cython cythonize