網(wǎng)站首頁 編程語言 正文
python和C/C++混合編程,推薦使用python的內(nèi)置模塊ctypes
,從名字上可以看出是c,可見對C++的支持并不太好。
一般的步驟:
- 1、導(dǎo)入ctypes模塊,加載C/C++ dll到python進程空間
- 2、python類型轉(zhuǎn)換為ctypes類型
- 3、ctypes類型轉(zhuǎn)換為C/C++類型
ctypes文檔
VS2017 + Python3.8(IDE:py Charm)
基本數(shù)據(jù)類型以及結(jié)構(gòu)體類型都可以正常通信。
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") #調(diào)用 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)
如果結(jié)構(gòu)體嵌套,也是可以成功傳輸?shù)模窃陧椖亢艽髸r可能會遇到大結(jié)構(gòu)體通信數(shù)據(jù)錯誤,如char*傳到C/C++端為無效的字符。
建議,將結(jié)構(gòu)體按照先簡單和復(fù)雜的順序排列成員。
參考官方文檔為python和C/C++中的結(jié)構(gòu)體定義字節(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) ]
原文鏈接:https://www.cnblogs.com/MakeView660/p/12486936.html
相關(guān)推薦
- 2022-11-10 rust延遲5秒鎖屏的實現(xiàn)代碼_相關(guān)技巧
- 2022-04-01 FastDFS服務(wù)不能上傳文件 報錯:fileutil.MyException: getStoreS
- 2022-08-04 GoFrame框架gset交差并補集使用實例_Golang
- 2022-07-26 Python的基本數(shù)據(jù)類型
- 2022-11-03 C++高精度算法的使用場景詳解_C 語言
- 2022-09-17 go單體日志采集zincsearch方案實現(xiàn)_Golang
- 2022-05-08 React的事件處理你了解嗎_React
- 2023-03-22 淺談C#中[]的幾種用法_C#教程
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支