1、介紹
Python作為一個(gè)開發(fā)效率高的腳本語言,在開發(fā)商比較有效率。而底層庫大都是C++編寫的,效率高。因此開發(fā)的時(shí)候遇到對效率要求高的時(shí)候采用C++編寫庫。這就需要封裝一個(gè)接口給Python腳本去調(diào)用。
2、代碼
直接上代碼吧。編譯器用的是VS2017

image.png
選擇DLL文件,確定之后刪掉預(yù)編譯頭那些東西。選擇環(huán)境為x64。

image.png

image.png

image.png
環(huán)境要選對,因?yàn)?4位的Python調(diào)用不了x86環(huán)境編寫的DLL(32位)。
DllTest.h
#pragma once
#include <iostream>
class DllTest {
double a;
double b;
public:
void SetParam(double _a, double _b);
void DisplayParam();
int AddParam();
};
DllTest.cpp
#include "DllTest.h"
void DllTest::SetParam(double _a, double _b)
{
a = _a;
b = _b;
}
void DllTest::DisplayParam()
{
std::cout << "a = " << a << ", b = " << b << std::endl;
}
int DllTest::AddParam()
{
return static_cast<int>(a + b);
}
dllmain.cpp
#include "DllTest.h"
extern "C" {
DllTest d;
__declspec(dllexport) void Set(double _a, double _b)
{
d.SetParam(_a, _b);
}
__declspec(dllexport) void Print()
{
d.DisplayParam();
}
__declspec(dllexport) int Add()
{
return d.AddParam();
}
}
直接生成,在目標(biāo)路徑下就會生成一個(gè)Dll1.dll文件,將這個(gè)文件復(fù)制到Python腳本的目錄下。

image.png

image.png
Python代碼如下:
test.py
import ctypes
# 加載動態(tài)鏈接庫
cpp = ctypes.cdll.LoadLibrary("Dll1.dll")
# 設(shè)置Set函數(shù)的形參類型
cpp.Set.argtypes = [ctypes.c_double, ctypes.c_double]
# 設(shè)置Add函數(shù)的返回值類型
cpp.Add.restype = ctypes.c_int
# 調(diào)用Set,Print和Add函數(shù)
cpp.Set(1.0, 2.0)
cpp.Print()
print(cpp.Add())
輸出結(jié)果為:

image.png
這樣便可以成功調(diào)用C++編寫的動態(tài)鏈接庫了。
結(jié)語
閑暇記錄一下代碼,方便自己回看,如果能幫到你就更好了。