这是我的最小示例代码。
import ctypes as c
import numpy as np
import subprocess
## the c code
c_code = """
#include<string.h>
#include<stdlib.h>
typedef struct My_Struct_{
int n;
float *b;
}My_Struct;
My_Struct *my_struct_new(int n) {
My_Struct *result = malloc(sizeof *result);
result->n = n;
result->b = malloc(n*sizeof result->b[0]);
memset(result->b,1.0,n*sizeof result->b[0]);
return result;
}
"""
## creating the so file
with open('temp.c', 'w') as f:
f.write(c_code)
cmmd = "gcc -std=c99 -lm -shared -o temp.so -fPIC temp.c -lm -Wall -pedantic"
print subprocess.call(cmmd, shell=True)
## importing the so file
c_foo=c.cdll.LoadLibrary("./temp.so")
n = 5
class My_Struct(c.Structure):
_fields_= [("n",c.c_int),
("b",c.POINTER(c.c_float*n))]
my_struct_new = c_foo.my_struct_new
my_struct_new.argtype = [c.c_int]
my_struct_new.restype = c.POINTER(My_Struct)
## creating the struct
p_my_struct = my_struct_new(n)
# trying to read from the struct
print p_my_struct.contents.b[0]
print np.ctypeslib.as_array(p_my_struct.contents.b, (n,1))
但不是预期的
[[1.0, 1.0, 1.0, 1.0, 1.0]]
我得到:
<__main__.c_float_Array_5 object at 0x35fe3b0>
[[]
[�@�^]
[��A��������]
[`��J�]
[t*Op]]