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

猜你喜欢

转载自www.cnblogs.com/xiao-yyyy/p/11435480.html