python调用c++
c++文件中声明以c的方式编译
extern "C"{
Test* test_new(){return new Test;}
double my_calculate(Test* t, int a, double b, char c[], int * d, double * e, char ** f){
return t->calculate(a, b,c,d,e,f);
}
}
其中: test_new()中创建了一个c++的Test类的实例,并返回 my_calculate()中传入Test的一个实例t, 并调用t的caculate()方法
c++文件编译成python调用的.so动态库
g++ -shared -Wl,-soname,test_jpeg_facedetect-o face.so -fPIC test_jpeg_facedetect.cpp
其中: test_jpeg_facedetect是临时的.o文件名 face.so 是编译成的的库文件名 test_jpeg_facedetect.cpp 是要编译的文件
编写python脚本
import ctypes
lib = ctypes.cdll.LoadLibrary('./test.so')
lib.my_calculate.restype = ctypes.c_double
def convert_type(input):
ctypes_map = {int:ctypes.c_int,
float:ctypes.c_double,
str:ctypes.c_char_p
}
input_type = type(input)
if input_type is list:
length = len(input)
if length==0:
print("convert type failed...input is "+input)
return
else:
arr = (ctypes_map[type(input[0])] * length)()
for i in range(length):
arr[i] = bytes(input[i],encoding="utf-8") if (type(input[0]) is str) else input[i]
return arr
else:
if input_type in ctypes_map:
return ctypes_map[input_type](bytes(input,encoding="utf-8") if type(input) is str else input)
else:
print("convert type failed...input is "+input)
return
if __name__ == '__main__':
t = Test()
A1 = 123
A2 = 0.789
A3 = "C789"
A4 = [456,789]
A5 = [0.123,0.456]
A6 = ["A123", "B456"]
print(t.calculate(convert_type(A1), convert_type(A2), convert_type(A3),convert_type(A4),convert_type(A5),convert_type(A6)))
|