在python ctypes中作为参数传递字符串数组
这是对在Python ctypes中使用多维字符数组(字符串数组)的后续讨论。我有一个C语言的函数,它处理一个字符串数组。这个数据类型是静态的,所以这点很有帮助:
void cfunction(char strings[8][1024])
{
printf("string0 = %s\nstring1 = %s\n",strings[0],strings[1]);
strings[0][2] = 'd'; //this is just some dumb modification
strings[1][2] = 'd';
return;
}
我在Python中创建这个数据类型,并这样使用它:
words = ((c_char * 8) * 1024)()
words[0].value = "foo"
words[1].value = "bar"
libhello.cfunction(words)
print words[0].value
print words[1].value
输出看起来是这样的:
string0 = fod
string1 =
fod
bar
看起来我在把字符串对象传给我的C函数时出了点问题;它没有“看到”第二个数组的值,但在内存中写入这个位置并没有导致程序崩溃。
关于声明的字符串对象,还有一些奇怪的地方:
- words[0].value = foo
- len(words[0].value) = 3
- sizeof(words[0]) = 8
- repr(words[0].raw) = 'foo\x00\x00\x00\x00\x00'
为什么一个声明为1024个字符长的对象,给出的sizeof和raw值却是被截断的?
1 个回答
5
我觉得你需要把“words”定义成:
words = ((c_char * 1024) * 8)()
这将是一个长度为8的数组,每个元素都是长度为1024的字符串。