最近在作python3开发中,碰到了一个问题,须要经过调用C的一个动态连接库来获取相应的值。扒了扒网络,动手实践了下,造成此文。html
源码test.c
#includepython
要调用C库中的函数,须要用到ctypes这个模块
# -- coding: utf-8 --
author = ‘djstava’api
from ctypes import * handle = cdll.LoadLibrary('libtest.so') func = handle.printStr func.argtypes = (c_char_p,c_char_p) func.restype = c_char_p tmp = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8")) print(tmp.decode("utf-8"))
程序执行结果
helloworlddjstava网络
func.argtypes = (c_char_p,c_char_p) func.restype = c_char_p
这2句是分别设置参数数据类型和返回值类型,若是不进行设置,直接调用的话,参数能够正常接收,可是返回值永远是个int值,传入的字符串参数必须为encode(“utf-8”),不然在c库中仅会打印为首字符函数
handle = cdll.LoadLibrary('libtest.so') ret = handle.printStr("hello".encode("utf-8"),"world".encode("utf-8"))
关于其它数据类型的argtypes的设置,请查阅参考文献中的连接。rest