前几天写一个项目要用Python调用C++的.so文件,上网搜了一下,使用Python的ctypes模块
python官方文档:https://docs.python.org/2/library/ctypes.html?highlight=ctypes#module-ctypes
代码:
from ctypes import *
test = cdll.LoadLibrary(" ./certificate.so ")
print test
testpy = test.loadFile //loadFile是C++函数
ss = "/systemInfo.sys" // 向 loadFile传的参数
params = testpy(ss)
print params
运行脚本后,发现params是一堆乱码。调试之后,发现Python传到C++函数中的参数是乱码,也就是传的参数不对。到Python官方文档上查了一下,看了ctypes定义的原始C兼容数据类型. loadFile的参数类型是char*形式的,看了ctypes定义的数据类型后,“ss = "/systemInfo.sys" ”换成” ss = c_char_p(" /systemInfo.sys ") “ ,运行后还是乱码,就耐着性子继续在官网上看,发现” It is possible to specify the required argument types of functions exported fromDLLs by setting theargtypes attribute.“ 可以通过设置argtypes的属性值来指定dll传到C中的参数。
修改后的代码:
from ctypes import *
test = cdll.LoadLibrary(" ./certificate.so ")
print test
testpy = test.loadFile //loadFile是C++函数
testpy.argtype = c_char_p
ss = "/systemInfo.sys" // 向 loadFile传的参数
params = testpy(ss)
print params
再一次运行后,参数能传正常了,但返回值params却是一个int值,很奇怪,以为是返回了对象的地址,查了一下不是。又看了一下文档,By default functions are assumed to return the Cint type. Otherreturn types can be specified by setting therestype attribute of thefunction object. 原来默认返回的是C中的int值,可以通过设置restype来设置返回值。
修改后的代码:
from ctypes import *
test = cdll.LoadLibrary(" ./certificate.so ")
print test
testpy = test.loadFile //loadFile是C++函数
testpy.argtype = c_char_p //这里是testy.argtype而不是testy..argtypes
testpy.restype = c_char_p
ss = "/systemInfo.sys" // 向 loadFile传的参数
params = testpy(ss)
print params
运行一下,终于正确的返回string了。这里是testy.argtype而不是testy..argtypes,当参数多于2个时才用argtypes,例如:encodeFile.argtypes = [c_char_p, c_char_p]