【问题标题】:Multi-dimensional char array (array of strings) in python ctypespython ctypes中的多维char数组(字符串数组)
【发布时间】:2010-11-04 21:22:44
【问题描述】:

我正在尝试使用 ctypes 将字符数组的数组传递给 C 函数。

void cfunction(char ** strings)
{
 strings[1] = "bad"; //works not what I need.
 strings[1][2] = 'd'; //this will segfault.
 return;
}

char *input[] = {"foo","bar"};
cfunction(input);

因为无论如何我抛出的数组都是静态定义的, 我只是像这样更改了函数声明和输入参数:

void cfunction(char strings[2][4])
{
 //strings[1] = "bad"; //not what I need.
 strings[1][2] = 'd'; //what I need and now it works.
 return;
}

char input[2][4] = {"foo","bar"};
cfunction(input);

现在我遇到了如何定义这个多维字符的问题 python中的数组。我原以为会是这样:

import os
from ctypes import *
libhello = cdll.LoadLibrary(os.getcwd() + '/libhello.so')
input = (c_char_p * 2)()
input[0] = create_string_buffer("foo")
input[1] = create_string_buffer("bar")
libhello.cfunction(input)

这给了我TypeError: incompatible types, c_char_Array_4 instance instead of c_char_p instance。如果我将其更改为:

for i in input:
 i = create_string_buffer("foo")

然后我得到分段错误。此外,这看起来像是构建二维数组的错误方法,因为如果我打印输入,我会看到 None:

print input[0]
print input[1]

# outputs None, None instead of "foo" and "foo"

我还遇到了使用 #DEFINE MY_ARRAY_X 2#DEFINE MY_ARRAY_Y 4 将数组维度直接保存在我的 C 文件中的问题,但不知道从 libhello.so 中获取这些常量的好方法,以便 python在构造数据类型时可以引用它们。

【问题讨论】:

  • @user17925 对此有何反馈?
  • @Purcaru 看起来不错;我将您的构造工作到我的代码中,并且成功了! python 文档提供了 create_string_buffer 辅助函数,所以我想我只是决定使用它。

标签: python multidimensional-array ctypes


【解决方案1】:

使用类似的东西

input = ((c_char * 4) * 2)()
input[0].value = "str"
input[0][0] == "s"
input[0][1] == "t" # and so on...

简单用法:

>>> a =((c_char * 4) * 2)()
>>> a
<__main__.c_char_Array_4_Array_2 object at 0x9348d1c>
>>> a[0]
<__main__.c_char_Array_4 object at 0x9348c8c>
>>> a[0].raw
'\x00\x00\x00\x00'
>>> a[0].value
''
>>> a[0].value = "str"
>>> a[0]
<__main__.c_char_Array_4 object at 0x9348c8c>
>>> a[0].value
'str'
>>> a[0].raw
'str\x00'
>>> a[1].value
''
>>> a[0][0]
's'
>>> a[0][0] = 'x'
>>> a[0].value
'xtr'

【讨论】:

  • 谢谢。这真是太棒了!
猜你喜欢
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 2021-09-17
  • 2020-09-12
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
相关资源
最近更新 更多