python中调用C++有点麻烦,按我目前的经验,需要导出成C
而且在windows下编译成dll动态库的时候,只写 extern "C"{} 是不行的。因为还要把方法输出到动态库,否则仍然还是找不到。
比如我这样写的时候,仍然是不行的: 应该是动态库中无法找到相关函数的入口标识符。
需要添加库导出的修饰语句。比如这样:
#define C_DLL_EXPORT extern "C" __declspec(dllexport)
#define DLLEXPORT __declspec(dllexport)
#define C_DLL_EXPORT extern "C" __declspec(dllexport)
// // 方法1
// TestLib obj;
// C_DLL_EXPORT void __stdcall display() {
// obj.display();
// }
// C_DLL_EXPORT void __stdcall display_int() {
// obj.display(2);
// }
//
// C_DLL_EXPORT void __stdcall setPara(int a, int b) {
// printf("setPara a=%d, b=%d \r\n", a, b);
// obj.setParam(a, b);
// }
//
// C_DLL_EXPORT int __stdcall getSum() {
// return obj.getSum();
// }
// // 方法2
extern "C"
{
TestLib obj;
DLLEXPORT void __stdcall display() {
obj.display();
}
DLLEXPORT void __stdcall display_int() {
obj.display(2);
}
DLLEXPORT void __stdcall setPara(int a, int b) {
printf("setPara a=%d, b=%d \r\n", a, b);
obj.setParam(a, b);
}
DLLEXPORT int __stdcall getSum() {
return obj.getSum();
}
}
TestLib是一个简单的C++类:
#include <string>
#include <stdio.h>
#include <iostream>
using namespace std;
class TestLib {
public:
TestLib() { m_a = 0; m_b = 0; }
~TestLib() {}
void display();
void display(int a);
void setParam(int a, int b);
int getSum() {
return m_a + m_b;
}
private:
int m_a, m_b;
};
void TestLib::display() {
cout << "First display" << endl;
}
void TestLib::display(int a) {
cout << "Second display" << endl;
}
void TestLib::setParam(int a, int b) {
m_a = a;
m_b = b;
}
如此编译成功后,即可在python中进行调用了。
##### Python3.6
import ctypes
so = ctypes.CDLL('./HelloCpp2.dll')
so.hello()
so.display()
so.display_int(1)
so.setPara(1,2)
print('sum=', so.getSum())
运行结果如下: