python 使用ctypes调用C/C++ dll详情

作者:我来乔23 时间:2023-03-30 06:00:57 

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)

python 使用ctypes调用C/C++ dll详情

基本数据类型以及结构体类型都可以正常通信。
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

标签:ctypes,C++,dll
0
投稿

猜你喜欢

  • 使用Python matplotlib绘制简单的柱形图、折线图和直线图

    2022-04-08 02:13:19
  • Python魔术方法详解

    2022-04-25 00:13:05
  • SQL Server 2005安装配置方法图文教程 完美兼容Win7所有版本

    2024-01-21 04:38:43
  • php strstr查找字符串中是否包含某些字符的查找函数

    2023-11-17 01:42:23
  • 使用python调用浏览器并打开一个网址的例子

    2023-04-20 00:34:23
  • 如何在python中使用selenium的示例

    2023-07-15 20:52:09
  • OpenCV 图像梯度的实现方法

    2023-07-14 08:25:43
  • expression为什么性能差?

    2009-05-28 19:12:00
  • PHP 图片上传代码

    2024-05-22 10:05:49
  • python 基于dlib库的人脸检测的实现

    2022-08-23 22:59:07
  • python实现五子棋小游戏

    2023-02-28 08:37:59
  • Mac 安装和卸载 Mysql5.7.11 的方法

    2024-01-23 16:09:58
  • 解析pip安装第三方库但PyCharm中却无法识别的问题及PyCharm安装第三方库的方法教程

    2023-05-17 04:25:43
  • 细化解析:转换 SQL数据库时的疑难问题

    2009-02-05 15:38:00
  • 利用JAVA反射,读取数据库表名,自动生成对应实体类的操作

    2024-01-14 23:58:29
  • Python的轻量级ORM框架peewee使用教程

    2021-09-01 06:55:21
  • 利用python进行文件操作

    2022-01-09 10:49:51
  • Python3内置模块之base64编解码方法详解

    2021-04-01 15:45:24
  • 聊聊python中的循环遍历

    2022-06-17 23:44:43
  • Linux下安装MySQL5.7.19问题小结

    2024-01-16 06:21:37
  • asp之家 网络编程 m.aspxhome.com