最近在作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