1、编写C++头文件及源代码。
2、使用cmake打包测试无问题。
3、添加关键字“extern C”。有必要的话修改C++函数参数类型。
4、编写python程序调用
from ctypes import *
infile = "./ball_vicon_09041823.txt".encode('utf-8')
outfile = "./ball_vicon_fixed_09041825.txt".encode('utf-8')
vdtpcs = cdll.LoadLibrary('./build/libvicondataprocess.so')
# TODO 添加静默参数
vdtpcs.processdata(c_char_p(infile), c_char_p(outfile))
print(vdtpcs)
print(vdtpcs.processdata)
注意对字符串的编解码。C++需要utf8编码,python有些库例如pandas不需要。
5、测试输出
注意:
1.python参数类型要与C++参数类型匹配
2.python3字符串默认编码Unicode,调用参数类型为char *的函数时主义转换为c_char_p
3.可以先测试so文件是否载入成功?函数对象是否可以访问?最后进行函数调用
参考:
https://docs.python.org/3/library/ctypes.html
https://stackoverflow.com/questions/27127413/converting-python-string-object-to-c-char-using-ctypes
https://www.docs4dev.com/docs/zh/python/3.7.2rc1/all/library-ctypes.html