[英]Cython how to convert char** to const char**?
I am trying to use Cython to write a wrapper around a C++ library. 我正在尝试使用Cython在C ++库周围编写包装器。 However, I am running into an issue now, as one of the functions in the library takes the parameter const char**
. 但是,我现在遇到了一个问题,因为库中的函数之一采用参数const char**
。 Apparently, C++ is unable to do this conversion, ( Why am I getting an error converting a 'float**' to 'const float**'? ) which leaves me in a dilemma, as I am passing in a list of strings, let's call it x
into the function, and I am trying to generate the corresponding char** object, let's call it a
, using malloc and a for loop: 显然,C ++无法进行这种转换(( 为什么在将'float **'转换为'const float **'时会出错? ),这使我陷入了困境,因为我正在传递字符串列表,让我们将其称为x
到函数中,然后尝试生成相应的char **对象,使用malloc和for循环将其称为a
:
def f(x):
cdef char** a = <char**> malloc(len(x) * sizeof(char*))
for index, item in enumerate(x):
a[index] = item
......
Is there a workaround here? 这里有解决方法吗? The only thing I can think of is using const_cast
, and I can't find any details of whether or not that is implemented in Cython.... 我唯一能想到的就是使用const_cast
,我找不到关于是否在Cython中实现的任何详细信息。
The following code compiles in cPython V20.0. 以下代码在cPython V20.0中编译。 Does that solve your problem? 这样可以解决您的问题吗?
# 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
There is this old answer but I would implement to_cstring_array
little bit differently (use of strdup
, no PyString_AsString
) 有这个老答案,但是我会以不同的方式实现to_cstring_array
(使用strdup
,没有PyString_AsString
)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.