Python调用C++ 编写的dll动态库函数

前两篇博客是c++调用python程序:
C++调用Python函数(二)——调用函数并输出返回值
C++调用Python函数(一)——配置及测试

一丶C++ 编译类动态库

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

#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;
}

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

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

//test.h
#pragma once
class Mymath {
    int sum(int, int);
    int sub(int, int);
};

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

二丶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)

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

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

猜你喜欢

转载自blog.csdn.net/weixin_38285131/article/details/81288338