python?使用ctypes調用C/C++?dll詳情
python和C/C++混合編程,推薦使用python的內置模塊ctypes
,從名字上可以看出是c,可見對C++的支持并不太好。
一般的步驟:
- 1、導入ctypes模塊,加載C/C++ dll到python進程空間
- 2、python類型轉換為ctypes類型
- 3、ctypes類型轉換為C/C++類型
VS2017 + Python3.8(IDE:py Charm)
基本數(shù)據類型以及結構體類型都可以正常通信。
DLL:
extern "C"{ struct MyStruct{ int num_int; long num_long; float num_float; double num_double; char* num_str; }; int __declspec(dllexport) print(MyStruct my) printf("%d\n", my.num_int); printf("%d\n", my.num_long); printf("%f\n", my.num_float); printf("%f\n", my.num_double); printf("%s\n", my.num_str); }
PYTHON:
import ctypes class MyStruct(Structure): _fields_ = [ ("num_int", c_int), ("num_long", c_long), ("num_float", c_float), ("num_double", c_double), ("num_str", c_char_p) ] # dll全路徑,依賴完整 dll = ctypes.WinDLL("C:\\work\\mytest.dll") #調用 my = MyStruct(); my.num_int = 23 my.num_long = 1024 my.num_float = 3.14 my.num_double = 3.141592653 my.num_str = b"hello world" dll.print(my)
如果結構體嵌套,也是可以成功傳輸?shù)模窃陧椖亢艽髸r可能會遇到大結構體通信數(shù)據錯誤,如char*傳到C/C++端為無效的字符。
建議,將結構體按照先簡單和復雜的順序排列成員。
參考官方文檔為python和C/C++中的結構體定義字節(jié)對齊。
如:
<strong>#pragma pack(4)</strong> struct MyStruct{ int num_int; long num_long; float num_float; double num_double; char* num_str; };
class MyStruct(Structure): <strong>_pack_ </strong><strong>= 4</strong> _fields_ = [ ("num_int", c_int), ("num_long", c_long), ("num_float", c_float), ("num_double", c_double), ("num_str", c_char_p) ]
到此這篇關于python 使用ctypes調用C/C++ dll詳情的文章就介紹到這了,更多相關python調用C++ dll內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python用requests模塊實現(xiàn)動態(tài)網頁爬蟲
大家好,本篇文章主要講的是Python用requests模塊實現(xiàn)動態(tài)網頁爬蟲,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02Python連接Mysql實現(xiàn)圖書借閱系統(tǒng)
這篇文章主要為大家詳細介紹了Python連接Mysql實現(xiàn)圖書借閱系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03