我正在尝试将共享C库与某些python代码连接起来.与库的接口是这样的
typedef struct{
int v1;
double* v2} input;
Run Code Online (Sandbox Code Playgroud)
还有另外两种类型,例如:配置和输出类型.
我在python中使用ctypes Structure如下设置这些结构:
class input(Structure):
_fields_ = [("v1",c_int),("v2",POINTER(c_double)]
Run Code Online (Sandbox Code Playgroud)
C代码有一些函数接收指向该结构的指针,argtypes定义如下:
fun.argtypes = [constraints,input,POINTER(input)]
Run Code Online (Sandbox Code Playgroud)
constraints是另一个具有一些int配置字段的结构.
首先,我更新输入结构中的v2字段
input.v2 = generated_array.ctypes.data_as(POINTER(c_double))
Run Code Online (Sandbox Code Playgroud)
然后我称之为:
fun(constraints,input,byref(output))
Run Code Online (Sandbox Code Playgroud)
函数原型请求struct和*to struct(假设输出结构类型与输入结构类型相同).
然后我想访问存储在输出的v2字段中的乐趣结果.但是我得到了意想不到的结果.这样做有更好/更正确的方法吗?
我在这里搜索了很多并阅读了文档,但我找不到有什么问题.我没有任何错误消息,但是我从共享库中收到的警告似乎表明这些接口存在错误.
我猜我发现了这个问题:
当我调用该方法时,会调用一个numpy数组.然后我创建了4个向量:
out_real = ascontiguousarray(zeros(din.size,dtype=c_double))
out_imag = ascontiguousarray(zeros(din.size,dtype=c_double))
in_real = ascontiguousarray(din.real,dtype = c_double)
in_imag = ascontiguousarray(din.imag,dtype = c_double)
Run Code Online (Sandbox Code Playgroud)
其中din是输入向量.我用这种方式测试了方法:
print in_real.ctypes.data_as(POINTER(c_double))
print in_imag.ctypes.data_as(POINTER(c_double))
print out_real.ctypes.data_as(POINTER(c_double))
print out_imag.ctypes.data_as(POINTER(c_double))
Run Code Online (Sandbox Code Playgroud)
结果是:
<model.LP_c_double object at 0x1d81f80>
<model.LP_c_double object at 0x1d81f80>
<model.LP_c_double object at 0x1d81f80>
<model.LP_c_double object at 0x1d81f80> …Run Code Online (Sandbox Code Playgroud)