【发布时间】: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