最近小編由於需要,要在python項目中使用c++的一些類庫,遇到一些問題與大家分享。
首先我在VS中新建空的c++項目,項目結構如下:
頭文件test.h代碼如下:
#pragma once
#ifndef TEST_H
#define TEST_H
#include <cstring>
class test
{
public:
test();
~test();
double add(double x, double y);
char* strAdd(char* str1, char* str2);
};
struct TestStruct
{
double x;
double y;
};
extern "C" __declspec(dllexport) double addd(struct TestStruct &st);
#endif // !TEST_H
源文件test.cpp如下:
#include "test.h"
test::test()
{
}
test::~test()
{
}
double test::add(double x, double y)
{
return x + y;
}
char * test::strAdd(char * str1, char * str2)
{
return strcat(str1, str2);
}
test t;
extern "C" __declspec(dllexport) double add(double x, double y) {
return t.add(x, y);
}
extern "C" __declspec(dllexport) char* stradd(char * str1, char * str2) {
return t.strAdd(str1, str2);
}
double addd(struct TestStruct &st)
{
st.x = 2.5;
st.y = 3.1;
return st.x + st.y;
}
在VS中生成dll,右鍵項目->屬性->常規->項目默認值(配置類型)選擇.dll即可,注意你是配置的debug合適release版本與你當前編譯版本一致。
另外我使用的是ctypes類庫需要使用c語言編譯的dll庫,所以需要在方法函數前加extern "C" __declspec(dllexport)這一句__declspec(dllexport)是爲了保持函數名稱不變,否則編譯後函數名稱改變導致無法找到對應的函數。相關請看鏈接:
Exporting C++ Functions for Use in C-Language Executables
Exporting from a DLL Using __declspec(dllexport)
python代碼如下(我把生成的dll放在python代碼文件同一目錄的,你可以隨意放置):
# 開發人員:wxj233
# 開發時間:2019/12/29 17:22
import ctypes
dll = ctypes.cdll.LoadLibrary("pythonDll.dll") # 加載庫
dll.add.restype = ctypes.c_double # 指定返回值類型
dll.add.argtypes = (ctypes.c_double, ctypes.c_double) # 指定參數類型
print(dll.add(1.1, 1.4))
# 編輯結構體
class TestStruct(ctypes.Structure):
_fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)]
testStruct = TestStruct(1, 2)
dll.addd.restype = ctypes.c_double
print(dll.addd(ctypes.byref(testStruct))) # ctypes.byref() 傳遞引用
print(testStruct.x,testStruct.y)
輸出結果:2.5
5.6
2.5 3.1
關於ctypes相關可以參考下列文檔:
http://www.360doc.com/content/19/0417/02/9482_829313229.shtml(ctypes中文文檔)
最全ctypes用法總結
ctypes — A foreign function library for Python
Python實例淺談之三Python與C/C++相互調用