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 转载

相关推荐
倒头就睡的小比特1 天前
算法竞赛C++常用的STL
c++·算法
默_笙1 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
weilx12341 天前
C++笔记-文件IO-<fcntl.h>
c++
qq_426003961 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫1 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技1 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读1 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛1 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
只睡四小时1 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车1 天前
C/C++ 为什么需要编译器?
开发语言·c++