Windows下Python調用dll的教程網上有很多,包括返回常規變量和結構體變量的方法,但是返回數組的相關文章很少,這里通過一個簡單的例子介紹通過ctypes模塊調用dll返回數組的方法。
在test.cpp文件中添加如下測試函數:
float* ctest(float a) { static float x[3]; // 返回的數組必須是全局變量或者靜態變量 x[0] = a; x[1] = a * a; x[2] = a * a * a; return x; }
用VS或者其他工具編譯生成test.dll,創建test.py文件鏈接C函數和python函數:
import ctypes funtest = ctypes.cdll.LoadLibrary('./test.dll') # dll文件與py文件在同一目錄下 funtest.ctest.restype = ctypes.POINTER(ctypes.c_float*3) # 設置返回值為指向3個float數據的指針 class cfun(object): def __init__(self): pass def ctest(self, a): return funtest.ctest(ctypes.c_float(a)) # 將實參轉換為C語言中的類型
在main.py中導入test中的函數cfun類並實例化,調用ctest函數進行驗證:
from test import cfun c = cfun() pfloat = c.ctest(1.2) print(pfloat.contents[0]) print(pfloat.contents[1]) print(pfloat.contents[2]) ''' 輸出: 1.2000000476837158 1.440000057220459 1.7280001640319824 '''