c++ - 如何将字符串从 Python3 传递给 cythonized C++ 函数

标签 c++ python-3.x cython cythonize

我想了解如何在 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;
}

最佳答案

除了原始代码中的错误外,我设法使其与以下 source.pyx 一起工作(Python3 中的 bytes 类型与 C++ 中的 char* 之间的转换):

cdef extern from "source.cpp":
  cdef char* fun(char* param)

def pyfun(mystring):
  mystring_b = mystring.encode('utf-8')
  rvalue = fun(mystring_b).decode('utf-8')
  return rvalue

如果使用malloc分配内存在 fun 内它还需要被释放,否则会发生内存泄漏(当使用 C 指针时,总是值得考虑谁拥有内存)。这样做的修改版本是:

from libc.stdlib cimport free

# cdef extern as before

def pyfun(mystring):
    cdef char* value_from_fun
    mystring_b = mystring.encode('utf-8')
    value_from_fun = fun(mystring_b)
    try:    
        return value_from_fun.decode('utf-8')
    finally:
        free(value_from_fun)

类型转换的方式与以前相同。


编辑

根据 hpaulj在原始问题中的评论,这里是带有 libcpp.string 的版本映射 C++ std::string<string> 中定义:

from libcpp.string cimport string

cdef extern from "source.cpp":
  cdef string fun(string param)

def pyfun(mystring):
  mystring_ = mystring.encode('utf-8')
  rvalue = fun(mystring_).decode('utf-8')
  return rvalue

关于c++ - 如何将字符串从 Python3 传递给 cythonized C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42678779/

相关文章:

c++ - std::hex 和 std::setw 不适用于某些字符

python - 为什么我将四个字节转换为二进制只有 30 个二进制数字?

python - 在 Cython 代码中使用 float 文字而不是 double?

c++ - while语句不会停止

c++ - MakeStream::iterate() 的 Range V3 是什么?

sql - Psycopg2 连接类属性

python - 如何在networkx中的函数定义中调用图形?

cython:如何声明一个没有返回值的 cdef 函数

python - Cython 和 regex.h

c++ - 表达式未计算为常量- c++