【问题标题】:Passing array of strings as parameter in python ctypes在python ctypes中将字符串数组作为参数传递
【发布时间】:2010-11-11 16:58:20
【问题描述】:

这是对Multi-dimensional char array (array of strings) in 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 对象还有一些奇怪的地方:

  • 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 和原始值?

【问题讨论】:

    标签: python pointers ctypes


    【解决方案1】:

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

    words = ((c_char * 1024) * 8)()
    

    这将是一个长度为 8 的数组,其中包含长度为 1024 的字符串。

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 2020-09-12
      • 2017-08-10
      • 2017-06-14
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      相关资源
      最近更新 更多