文章目录
举个例子
1.1 基础C++代码
calculate.h
#pragma once
#include <windows.h>
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
calculate.cpp
#include "calculate.h"
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
return a / b;
}
1.2 需要做的操作
1.2.1 添加 dll.h
#pragma once
#ifndef DLL_H_
#define DLL_H_
extern "C" _declspec(dllexport) int testAdd(double a, double b);
extern "C" _declspec(dllexport) int testSubtract(double a, double b);
extern "C" _declspec(dllexport) int testMultiply(double a, double b);
extern "C" _declspec(dllexport) int testDivide(double a, double b);
#endif
查看关于extern “C” _declspec(dllexport)的解释点这里,不想看得直接替换自己的方法即可。
1.2.2 添加 dll.cpp
//dll.cpp
#include <iostream>
#include <windows.h>
#include "calculate.h"
extern "C" _declspec(dllexport)int testAdd(double a, double b)
{
double r = add(a, b);
return r;
}
extern "C" _declspec(dllexport)int testSubtract(double a, double b)
{
double r = subtract(a, b);
return r;
}
extern "C" _declspec(dllexport)int testMultiply(double a, double b)
{
double r = multiply(a, b);
return r;
}
extern "C" _declspec(dllexport)int testDivide(double a, double b)
{
double r = divide(a, b);
return r;
}
1.2.3 修改配置动态库
看图操作
1.2.3 生成解决方案
输出里会打印dll输出路径
1.2.3 查找依赖库
输入命令: dumpbin /dependents dll文件所在路径(执行上一步会在输出框里打印dll文件所在路径)
从C:\Windows\System32目录下找这些依赖的dll文件,复制到dll文件所在目录下。
1.3 python调用测试
使用ctypes 调用c++代码
from ctypes import CDLL, wintypes
dll = CDLL('dll所在路径')
# 参数类型
dll.testAdd.argtypes = [wintypes.DOUBLE, wintypes.DOUBLE]
# 返回值类型
dll.testAdd.restype = wintypes.DOUBLE
r1 = dll.testAdd(3.2, 2.1)
dll.testSubtract.argtypes = [wintypes.DOUBLE, wintypes.DOUBLE]
dll.testSubtract.restype = wintypes.DOUBLE
r2 = dll.testSubtract(3.2, 2.1)
dll.testMultiply.argtypes = [wintypes.DOUBLE, wintypes.DOUBLE]
dll.testMultiply.restype = wintypes.DOUBLE
r3 = dll.testMultiply(3.2, 2.1)
dll.testDivide.argtypes = [wintypes.DOUBLE, wintypes.DOUBLE]
dll.testDivide.restype = wintypes.DOUBLE
r4 = dll.testDivide(3.2, 2.1)
print(r1, r2, r3, r4)
# 输出结果
# 5.300000000000001 1.1 6.720000000000001 1.5238095238095237