Python ctypes:传递字符串数组 [英] Python ctypes: Passing an array of strings
问题描述
我在Python 2.7中有一个字符串数组,我想通过 ctypes
传递给C函数:
I have an array of strings in Python 2.7, which I would like to pass to a C function via ctypes
:
unsigned int SetParams(unsigned int count, const char **params)
所以我可以在python中定义参数:
So I can define the parameters in python:
import ctypes as ct
lib = ct.cdll.LoadLibrary('...')
lib.SetParams.restype = ct.c_uint
lib.SetParams.argtypes = [ct.c_uint, ct.POINTER(ct.c_char_p)]
但是现在当我想在上面的库调用中使用Python函数中的一组参数时,我实际上该如何调用它呢?我在想这样的事情:
but now when I am given a set of params in a Python function, which I would like to use in the above library call, how do I actually call it? I am thinking something like this:
def setParameters(strParamList):
numParams = len(strParamList)
strArrayType = ct.c_char_p * numParams
strArray = strArrayType()
for i, param in enumerate(strParamList):
strArray[i] = param
lib.SetParams(numParams, strArray)
我只是从 ctypes
开始,想知道是否有更自动化的方法来做到这一点?另外,赋值 strArray [i] = param
是否实际上在重新分配?如果是这样,这似乎很昂贵-是否有办法仅将字符串指针指向Python分配的缓冲区,或者它们不是NULL终止的?
I am just starting with ctypes
and wondering if there is a more automated way to do this? Also is the assignment strArray[i] = param
actually reallocating? If so, this seems quite expensive -- is there a way to do this just pointing the string pointers to Python-allocated buffers, or they are not NULL-terminated?
更新我确实浏览了几个相关的问题,但是找不到直接的问题来解决相同的问题.非常感谢
UPDATE I did look through a couple related questions, but could not find a direct one to deal with the same issues. Thank you very much
推荐答案
您认为正确.该代码有效.致电,例如:
You think correctly. That code works. Call with, for example:
setParameters(['abc','def','ghi'])
我没有查看源代码,但是Python 2.7(32位)上的 ctypes
确实通过了内部Python缓冲区(通过在C函数中修改传递的字符串并在输出之后打印它来进行测试)(在Python中称为调用"),这就是为什么您应该只将上述Python字符串传递给采用 const char *
的函数,或者至少已知不修改该字符串的原因.由于Python字符串是不可变的,因此在C语言下对它们的写入是不可取的.使用 ctypes.create_string_buffer
创建可写字符串,以传递给非常量 char *
.
I haven't looked at the source, but ctypes
on Python 2.7 (32-bit) does pass the internal Python buffer (tested by modifying the passed string in the C function and printing it after the call in Python), which is why you should only pass Python strings as above to functions that take const char*
or at least are known not to modify the string. Since Python strings are immutable writing to them under C is a no-no. Use ctypes.create_string_buffer
to create a writable string to pass to non-const char*
.
这篇关于Python ctypes:传递字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!