场景
ctypes能够将C代码打包成动态库供python调用, 其中接口部分有很多细节, 这里选择一个综合的例子, 试图尽可能多的呈现各种细节, 提高后续开发效率. 不保证代码完全正确.
C代码
struct Date{
int month;
int year;
}
typedef B{
int id
struct Date date;
unsigned char data[10];
unsigned char* str;
}
int func(B b1, B*b2){
b2 = &b1;
memcpy(b2, &b1, sizeof(b1));//引用传递记得拷贝
return 0;
}
python代码
from ctypes import *
class Date(Structure):
_field_ = [
("month", c_int),
("year", c_int)
]
class B(Structure):
_field_ = [
("id", c_int),
("date", Date), #自定义类型
("data", (c_ubyte*10)),#数组的用法
("str", POINTER(c_ubyte))#指针的用法
]# 参数顺序必须和c中一致
b1 = B(id=1,data=Date(1,2), data=(c_byte*10)(1,2,3,4,5,6,7,8,9,10))#可忽略
b2 = B()
libtest = CDLL("./libtest.so")
libtest.func(b1, byref(b2)) #引用传递
编译方法
gcc -fPIC test.c -o test.o
gcc -shared -o libtest.so test.o
如果动态库实在C中运行, 要把动态文件路径存到LD_LIBRARY_PATH
中