網站首頁 編程語言 正文
python和C/C++混合編程,推薦使用python的內置模塊ctypes
,從名字上可以看出是c,可見對C++的支持并不太好。
一般的步驟:
- 1、導入ctypes模塊,加載C/C++ dll到python進程空間
- 2、python類型轉換為ctypes類型
- 3、ctypes類型轉換為C/C++類型
ctypes文檔
VS2017 + Python3.8(IDE:py Charm)
基本數據類型以及結構體類型都可以正常通信。
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)
如果結構體嵌套,也是可以成功傳輸的,但是在項目很大時可能會遇到大結構體通信數據錯誤,如char*傳到C/C++端為無效的字符。
建議,將結構體按照先簡單和復雜的順序排列成員。
參考官方文檔為python和C/C++中的結構體定義字節對齊。
如:
<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
相關推薦
- 2022-08-20 ORACLE中dbms_output.put_line輸出問題的解決過程_oracle
- 2023-06-20 k8s應用監控探針詳解_云其它
- 2022-03-14 關于VS+QT5應用程序換圖標的解決方案_C 語言
- 2022-03-26 C語言關于時間復雜度詳解_C 語言
- 2022-08-15 SpringMVC異常處理流程總結
- 2022-05-23 Python學習之時間包使用教程詳解_python
- 2022-03-27 Linux上搭載Nginx負載均衡配置使用案例詳解_nginx
- 2023-07-15 oracle 序列/自增ID
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支