Python Cython如何将字符**转换为常量字符**? 我试图使用Cython来编写一个围绕C++库的包装器。但是,我现在遇到了一个问题,因为库中的一个函数使用参数const char**。很显然,C++无法进行转换,(这使我陷入困境,因为我在字符串列表中传递,我们将它称为代码>代码到函数中,我试图生成相应的char **对象,我们称之为代码,使用Maloc和for循环: def f(x): cdef char** a = <char**> malloc(len(x) * sizeof(char*)) for index, item in enumerate(x): a[index] = item ...... def(x): cdef char**a=malloc(len(x)*sizeof(char*)) 对于索引,枚举(x)中的项: a[索引]=项目 ......
这里有解决办法吗?我唯一能想到的就是使用Python Cython如何将字符**转换为常量字符**? 我试图使用Cython来编写一个围绕C++库的包装器。但是,我现在遇到了一个问题,因为库中的一个函数使用参数const char**。很显然,C++无法进行转换,(这使我陷入困境,因为我在字符串列表中传递,我们将它称为代码>代码到函数中,我试图生成相应的char **对象,我们称之为代码,使用Maloc和for循环: def f(x): cdef char** a = <char**> malloc(len(x) * sizeof(char*)) for index, item in enumerate(x): a[index] = item ...... def(x): cdef char**a=malloc(len(x)*sizeof(char*)) 对于索引,枚举(x)中的项: a[索引]=项目 ......,python,c++,cython,Python,C++,Cython,这里有解决办法吗?我唯一能想到的就是使用const\u cast,我找不到任何关于是否在Cython中实现的细节 以下代码在cPython V20.0中编译。这能解决你的问题吗 # distutils: language = c++ from libc.stdlib cimport malloc def f(x): cdef const char** a = <const char**> malloc(len(x) * sizeof(char*)) for ind
const\u cast
,我找不到任何关于是否在Cython中实现的细节 以下代码在cPython V20.0中编译。这能解决你的问题吗
# distutils: language = c++
from libc.stdlib cimport malloc
def f(x):
cdef const char** a = <const char**> malloc(len(x) * sizeof(char*))
for index, item in x:
a[index] = item
<代码> diditul:语言= C++
来自libc.stdlib cimport malloc
def f(x):
cdef const char**a=malloc(len(x)*sizeof(char*))
对于索引,x中的项:
a[索引]=项目
有这么一个旧的方法,但我将对数组的实现略有不同(使用strdup
,无PyString\u AsString
)
来自libc.stdlib cimport malloc,免费
从libc.string cimport strdup
cdef char**to_cstring_数组(列表字符串):
cdef常量字符*s
cdef大小\u t l=长度(字符串)
cdef char**ret=malloc(l*sizeof(char*))
#对于空终止数组
#cdef char**ret=malloc((l+1)*sizeof(char*))
#ret[l]=NULL
对于范围(l)中的i:
s=字符串[i]
ret[i]=strdup(s)
回程网
只要列表x
在某个地方被引用,该功能就可以工作。之后,数组指向已解除分配并可能重新使用的内存位置。另外,x
内容的更改可能会导致故障。
from libc.stdlib cimport malloc, free
from libc.string cimport strdup
cdef char ** to_cstring_array(list strings):
cdef const char * s
cdef size_t l = len(strings)
cdef char ** ret = <char **>malloc(l* sizeof(char *))
# for NULL terminated array
# cdef char ** ret = <char **>malloc((l + 1) * sizeof(char *))
# ret[l] = NULL
for i in range(l):
s = strings[i]
ret[i] = strdup(s)
return ret