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)
基本数据类型以及结构体类型都可以正常通信。
DLL:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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++中的结构体定义字节对齐。
如:
1
2
3
4
5
6
7
8
|
<strong>#pragma pack(4)</strong> struct MyStruct{ int num_int; long num_long; float num_float; double num_double; char * num_str; }; |
1
2
3
4
5
6
7
8
9
|
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内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/MakeView660/p/12486936.html