用Cython - 将字符串转换为char名单** [英] Cython - converting list of strings to char **
问题描述
我怎么能Python字符串的Python列表转换为空值终止的char **
这样我就可以把它传递给外部的C函数?
How can I convert a python list of python strings to a null-terminated char**
so I can pass it to external C function?
我有:
struct saferun_task:
saferun_jail *jail
saferun_limits *limits
char **argv
int stdin_fd
int stdout_fd
int stderr_fd
int saferun_run(saferun_inst *inst, saferun_task *task, saferun_stat *stat)
在CDEF的extern块
in cdef extern block
我想转换像('./ a.out的','参数1','参数2')
的东西,我可以分配给 saferun_task.argv
如何?
推荐答案
从用Cython文档:
From the Cython docs:
char* PyString_AsString (PyObject *string)
返回的字符串的内容一个空结束的重新presentation。该
指针指向字符串的内部缓冲区,而不是一个副本。数据
不能以任何方式被修改。它一定不能被解除分配
Returns a null-terminated representation of the contents of string. The pointer refers to the internal buffer of string, not a copy. The data must not be modified in any way. It must not be de-allocated.
我没有用Cython编译器的设置和方便的自动柜员机(我可以在以后运行,并核对),但是,这应该会导致code,看起来是这样的:
I don't have a Cython compiler setup and handy atm (I can run this later and check) but, this should results in code that looks something like:
from libc.stdlib cimport malloc, free
cdef char **string_buf = malloc(len(pystr_list) * sizeof(char*))
for i in range(len(pystr_list)):
string_buf[i] = PyString_AsString(pystr_list[i])
# Do stuff with string_buf as a char**
# ...
free(string_buf)
现在的指针的StringBuf是char **你的原始数据而不复制任何条件 - 虽然你不应该在每个字符串编辑数据作为字符串应该为const char *进行处理(从文档)。如果你需要操作字符串,你将不得不memcpy的数据,或使你不关心在Python捣毁新对象 - 尽管因为你有一个字符串的元组,我怀疑你编辑它们。
The pointer stringBuf is now a char ** to your original data without copying any strings -- though you shouldn't edit the data in each string as the strings should be treated as const char* (from docs). If you need to manipulate the strings you will have to memcpy the data or make new objects which you don't care about trashing in Python -- though since you have a tuple of strings I doubt you are editing them.
这篇关于用Cython - 将字符串转换为char名单**的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!