在python ctypes中传递字符串数组作为参数

use*_*925 1 python ctypes pointers

这是python ctypes中多维char数组(字符串数组)的后续内容.我有一个ac函数来操作一个字符串数组.数据类型是静态的,因此这有助于:

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;
}
Run Code Online (Sandbox Code Playgroud)

我在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
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

string0 = fod
string1 =
fod
bar
Run Code Online (Sandbox Code Playgroud)

看起来我不正确地将单词对象传递给我的C函数; 它不会//看到//第二个数组值,但写入内存中的位置不会导致段错误.

关于声明的单词对象的其他奇怪之处:

  • 单词[0] .value = foo
  • len(单词[0] .value)= 3
  • sizeof(words [0])= 8
  • repr(words [0] .raw)='foo\x00\x00\x00\x00\x00'

为什么一个对象被声明为1024个字符长,给出了截断的sizeof和raw值?

mjh*_*jhm 5

我认为您需要将单词定义为:

words = ((c_char * 1024) * 8)()
Run Code Online (Sandbox Code Playgroud)

这将是长度为1024的字符串长度为8的数组.