【发布时间】:2018-05-21 10:48:48
【问题描述】:
我正在尝试使用ctypes。我对操作包含数组的 C 结构感兴趣。考虑以下my_library.c
#include <stdio.h>
typedef struct {
double first_array[10];
double second_array[10];
} ArrayStruct;
void print_array_struct(ArrayStruct array_struct){
for (int i = 0; i < 10; i++){
printf("%f\n",array_struct.first_array[i]);
}
}
假设我已经在共享库 my_so_object.so 中编译了它,我可以通过 Python 执行类似的操作
import ctypes
from ctypes import *
myLib = CDLL("c/bin/my_so_object.so")
class ArrayStruct(ctypes.Structure):
_fields_ = [('first_array', ctypes.c_int * 10), ('second_array', ctypes.c_int * 10)]
def __repr__(self):
return 'ciaone'
myLib.print_array_struct.restype = None
myLib.print_array_struct.argtype = ArrayStruct
my_array_type = ctypes.c_int * 10
x1 = my_array_type()
x2 = my_array_type()
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x1[0:9] = a[0:9]
a = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
x2[0:9] = a[0:9]
print(my_array_type)
>>> <class '__main__.c_int_Array_10'>
print(x1[2])
>>> 3
print(x2[2])
>>> 13
x = ArrayStruct(x1, x2)
print(x.first_array[0:9])
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
到目前为止一切顺利:我已经创建了正确的类型,并且一切似乎都运行良好。但后来:
myLib.print_array_struct(x)
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
>>> 0.000000
我显然错过了一些东西。 ArrayStruct 类型已被识别(否则调用 myLib.print_array_struct(x) 会引发错误)但未正确初始化。
【问题讨论】:
-
注意 #1:您有
double(C) 与int(Python)。另外,它是:myLib.print_array_struct.argtypes = [ArrayStruct] -
这完全有效!我感到既感激又惭愧:D如果你愿意,你可以添加它作为答案,我会投票给它