Python调用c++生成的dll

Python调用c++生成的dll

1.简单例子

1.1 vs2019 c++生成dll

  • 项目中添加add.cpp文件
cpp 复制代码
extern "C" int __declspec(dllexport) add(int x, int y)
{
	return x + y;
}
  • 配置属性
  • 生成dll
    点击生成解决方案,到输出目录文件夹查看add.dll文件是否正常生成。

1.2 Python端调用

python 复制代码
from ctypes import*

import sys
try:
    mydll = cdll.LoadLibrary(r"add.dll")
except:
    sys.exit("No shared DLL/SO found")

print(mydll.add(3,4))
#7

2.调用c++类生成的dll

2.1 vs cpp端生成dll

  • 添加myDll.cpp文件
cpp 复制代码
#include<iostream>
using namespace std;
class myDll
{
public:
	void helloDll() 
	{
		cout << "hello dll" << endl;
	};
};


extern "C" 
{
	myDll obj;

	extern "C" _declspec(dllexport) void helloDll() 
	{
		return obj.helloDll();
	}
}
  • 配置属性

dll名设置为myDll.

  • 生成dll文件

参考第一个例子。

2.2 Python端调用

python 复制代码
from ctypes import*

import sys
try:
    mydll = cdll.LoadLibrary("myDll.dll")
except:
    sys.exit("No shared DLL/SO found")

mydll.helloDll()

#hello dll

测试通过!

参考文献

1\] [python调用dll 结构体 python如何调用dll 转载](https://blog.51cto.com/u_16099237/6548050)

相关推荐
星哥说事1 天前
Python自学25 - Django快速上手
开发语言·python·django
斑点鱼 SpotFish1 天前
用Python可视化国庆期间旅游概况与消费趋势
开发语言·python·旅游
小兔崽子去哪了1 天前
Python 学习记录
python
埃泽漫笔1 天前
RabbitMQ四种交换机详解
python·mq
小杰帅气1 天前
类与对象1
开发语言·c++
chenyuhao20241 天前
《C++二叉引擎:STL风格搜索树实现与算法优化》
开发语言·数据结构·c++·后端·算法
小猪快跑爱摄影1 天前
【附代码】Jupyter 多进程调用 seaborn 并保留格式
python·jupyter
空荡forevere1 天前
《操作系统真象还原》 第十章 输入输出系统
开发语言·c++·操作系统
技术猴小猴1 天前
如何使用Python实现LRU缓存
python·spring·缓存
2401_841495641 天前
【自然语言处理】“bert-base-chinese”的基本用法及实战案例
人工智能·python·自然语言处理·bert·文本预处理·特征提取·训练验证