我这样做,但得到了错误。在
使用ctypes有什么错误吗,或者我传递的参数类型有什么问题吗?在
我认为应该考虑三点:
在python中生成传递给c函数的正确参数。
将struct类型的指针传递给c函数。
如果需要python代码中的struct,则右实例化struct依赖于给定的数组。
我是c新手,尤其是指针。在
c代码:结构,ansfer.h
typedef unsigned char boolean_T;
struct emxArray_real_T
{
double *data;
int *size;
int allocatedSize;
int numDimensions;
boolean_T canFreeData;
};
python调用的函数ansfer.c
^{pr2}$然后,gcc -o libansfer.so -shared -fPIC *.c
在利班斯福生成。在
我重写了测试.py根据建议。按如下方式添加结构。在
python代码:测试.py在
import numpy as np
import ctypes
c_double_p = ctypes.POINTER(ctypes.c_double)
c_int_p = ctypes.POINTER(ctypes.c_int)
class emxArray_real_T(ctypes.Structure):
_fields_ = [
("data", c_double_p),
("size", c_int_p),
("allocatedSize", ctypes.c_int),
("numDimensions", ctypes.c_int),
("canFreeData", ctypes.c_bool)
]
indata = np.array([[1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.1],[2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2,2.2],[3.3,3.3,3.3,3.3,3.3,3.3,3.3,3.3,3.3,3.3,3.3,3.3,3.3,2.2,2.2,2.2]])
LL, CC = indata.shape
TE = np.zeros((LL,LL), dtype=np.double)
Lag = np.zeros((LL,LL), dtype=np.double)
SS = np.array([LL, CC])
instruct = emxArray_real_T()
instruct.data = c_double_p(ctypes.c_double(indata.ctypes.data))
instruct.size = c_int_p(ctypes.c_int(SS.ctypes.data))
instruct.allocatedSize = ctypes.c_int(LL*CC)
instruct.numDimensions = ctypes.c_int(2)
instruct.canFreeData = ctypes.c_bool(0)
ss = np.array([LL, LL])
outstruct1 = emxArray_real_T()
outstruct1.data = c_double_p(ctypes.c_double(TE.ctypes.data))
outstruct1.size = c_int_p(ctypes.c_int(ss.ctypes.data))
outstruct1.allocatedSize = ctypes.c_int(LL*LL)
outstruct1.numDimensions = ctypes.c_int(2)
outstruct1.canFreeData = ctypes.c_bool(0)
outstruct2 = emxArray_real_T()
outstruct2.data = c_double_p(ctypes.c_double(Lag.ctypes.data))
outstruct2.size = c_int_p(ctypes.c_int(ss.ctypes.data))
outstruct2.allocatedSize = ctypes.c_int(LL*LL)
outstruct2.numDimensions = ctypes.c_int(2)
outstruct2.canFreeData = ctypes.c_bool(0)
lib = ctypes.cdll.LoadLibrary('./libansfer.so')
lib.ansferA(instruct,ctypes.c_double(3), outstruct1, outstruct2)
但类似的错误
Traceback (most recent call last):
File "C:\Python27\testfile\test.py", line 106, in <module>
lib.ansferA(instruct,ctypes.c_double(3), outstruct1, outstruct2)
WindowsError: exception: access violation writing 0x0000000000000000
这不是一个答案,但格式化规则不允许我将其作为注释放置(并且仍然可读)。在
结构如下所示:
我不得不猜测,
canFreeData
的类型,boolean_T
不是标准的C类型。在然后用如下方法初始化结构:
^{pr2}$我没有使用过numpy,所以我不知道它的类型是否/如何映射到ctypes或常规python变量类型。在
相关问题 更多 >
编程相关推荐