【发布时间】:2020-06-27 15:32:01
【问题描述】:
我正在尝试创建类似于 numpy 的东西来了解 ctypes 的工作原理,但在将指向“Matrix”结构的指针传递给某些函数时遇到了问题。
调用 print_matrix 的输出总是一些随机整数,然后是几个空格。
我使用的是 Python 3.7.5,C 代码是使用以下代码编译的:gcc -shared -o libarray.so -fPIC array.c
C 代码:
typedef struct Matrix {
int *arr;
int *shape;
int dims;
} Matrix;
void print_matrix(Matrix *Mat) {
int num = 1;
for (int i = 0; i < Mat -> dims; i++) {num *= Mat -> shape[i];}
for (int i = 0; i < num; i++) {
printf("%d ", Mat -> arr[i]);
if (Mat -> dims >= 2) {
if (((i + 1) % Mat -> shape[0]) == 0) {
printf("\n");
}
}
}
}
Python 代码:
import ctypes as cty
class Matrix(cty.Structure):
_fields_ = [("arr", cty.POINTER(cty.c_int)), ("shape", cty.POINTER(cty.c_int)), ("dims", cty.c_int)]
libarray = cty.CDLL("./libarray.so")
print_matrix = libarray.print_matrix
print_matrix.restype = None
print_matrix.argtypes = [Matrix]
mat = Matrix((cty.c_int * 4)(*[1, 2, 3, 4]), (cty.c_int * 2)(*[2, 2]), cty.c_int(2))
print_matrix(mat)
我知道对于这个函数,我可以通过更改 print_matrix 代码直接传递 Matrix 结构,但是由于我的代码中的一些其他内容,我想主要处理指针。很抱歉这个奇怪的限制,提前感谢。
【问题讨论】: