python 调用c++类dll_python 调用c++ dll 动态库

一丶C++ 编译类动态库

1)新建生成.dll文件的空项目 这里写图片描述
双击: 这里写图片描述2)编写头文件:pycall.h

//test.h #pragma once class Mymath { int sum(int, int); int sub(int, int); }; 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

注:#define DLLEXPORT extern “C” __declspec(dllexport)
1. windows下需要使用__declspec(dllexport)的声明来说明这个函数是动态库导出的
2.extern “C”声明避免编译器对函数名称进行name mangling,这对于使用C++来编写DLL/SO是必须的。

3)编写实现文件:pycall_so.cpp

#define DLLEXPORT extern "C" __declspec(dllexport) #include"pycall.h" //两数相加 DLLEXPORT int sum(int a, int b) { return a + b; } //两数相减 DLLEXPORT int sub(int a, int b) { return a-b; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

然后生成解决方案: 这里写图片描述
生成了动态链接库和静态链接库

二丶python利用Ctypes调用C++动态库

把刚才生成的动态链接库放到.py文件夹下:

import ctypes import os CUR_PATH=os.path.dirname(__file__) dllPath=os.path.join(CUR_PATH,"mydll.dll") print (dllPath) #mydll=ctypes.cdll.LoadLibrary(dllPath) #print mydll pDll=ctypes.WinDLL(dllPath) print (pDll) pResutl= pDll.sum(1,4) pResult2=pDll.sub(1,4) print (pResutl) print (pResult2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

输出5和-3.
成功!!!

参考:
1.https://blog.csdn.net/adeen/article/details/49759033
2.https://blog.csdn.net/dongchongyang/article/details/52926310

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值