python在 linux上调用.so文件

  前几天写一个项目要用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]



    




  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值