日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python?使用ctypes調用C/C++?dll詳情_python

作者:我來喬23 ? 更新時間: 2022-06-27 編程語言

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

欄目分類
最近更新