加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python 调用c++ dll 动态库

发布时间:2020-12-20 10:50:02 所属栏目:Python 来源:网络整理
导读:一丶C++ 编译类动态库 1)新建生成.dll文件的空项目 双击: 2)编写头文件:pycall.h 1 2 3 4 5 6 7 //test.h #pragma once class Mymath { int sum( int , int ); int sub( int , int );}; 注:#define DLLEXPORT extern “C” __declspec(dllexport) 1. win

一丶C++ 编译类动态库

1)新建生成.dll文件的空项目


双击:


2)编写头文件:pycall.h

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

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

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

 
 
  • 7
  • 8
  • 9
  • 10
#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; }

然后生成解决方案:


生成了动态链接库和静态链接库

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

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

 
 
  • 10
  • 11
  • 12
  • 13
  • 14
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)

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读