[英]Calling c functions in python using ctypes
I'm trying to call c functions from python, I have the following code in c. 我试图从python调用c函数,我在c中有以下代码。
struct _returndata
{
double* data;
int row;
int col;
};
int mlfAddmatrixW(struct _returndata* retArr)
{
double data[] = {1,2,3,4,5,6,7,8,9}
retArr->row = 3;
retArr->col = 3;
memcpy(retArr->data, data, 9*sizeof(double));
return 1;
}
This is my code in python: 这是我在python中的代码:
class RETARRAY(Structure):
_fields_= [("data", c_double*9),
("row", c_int),
("col", c_int)]
if __name__ == '__main__':
dll = CDLL("/home/robu/Documents/tmo_compile/libmatrix/distrib/libmatrixwrapper.so")
#Initializing the matrix
retArr = pointer(RETARRAY())
for i in retArr.contents.data:
print i;
dll.mlfAddmatrixW(pointer(retArr))
for i in retArr.contents.data:
print i;
print retArr.contents.row
print retArr.contents.col
The content of the data has changed, but the col and row is still 0. How can I fix that? 数据的内容已更改,但col和row仍为0.我该如何解决? Is it possible to create a dynamic array in python , because in this case I created an array with 9 elements ("data", c_double*9),
. 是否可以在python中创建动态数组,因为在这种情况下我创建了一个包含9个元素的数组("data", c_double*9),
I know the size of the array after I called mlfAddmatrixW
function, the size of the array will be col*row
. 我在调用mlfAddmatrixW
函数后知道数组的大小,数组的大小将是col*row
。
You have a different struct in C and Python: one has a pointer to double, the other an array of doubles. 你在C和Python中有一个不同的结构:一个有一个指向double的指针,另一个指向一个双精度数组。 Try something like: 尝试类似的东西:
NineDoubles = c_double * 9
class RETARRAY(Structure):
_fields_= [("data", POINTER(c_double)),
("row", c_int),
("col", c_int)]
#Initializing the matrix
data = NineDoubles()
retArr = RETARRAY()
retArr.data = data
dll.mlfAddmatrixW(pointer(retArr))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.