環(huán)境:Window 10,VS 2019, Python 2.7.12, 64bit
1,打開(kāi) VS 2019,新建C++ Windows 動(dòng)態(tài)鏈接庫(kù)工程 Example,加入下列文件,如果Python是64位的則在VS中 Solution platforms 選擇 x64 編譯成64位的 DLL;
Example.h
#pragma once #ifndef CPP_EXPORTS #define CPP_EXPORTS #endif #ifdef CPP_EXPORTS #define CPP_API _declspec(dllexport) #else #define CPP_API _declspec(dllimport) #endif #includeusing namespace std; #ifdef __cplusplus extern "C" { #endif CPP_API int __cdecl getInt(); CPP_API const char* __cdecl getString(); CPP_API void __cdecl setString(const char* str); #ifdef __cplusplus } #endif
Example.cpp
#include "pch.h" #include "Example.h" CPP_API int __cdecl getInt() { return 5; } CPP_API const char* __cdecl getString() { return "hello"; } CPP_API void __cdecl setString(const char* str) { cout << str << endl; }
編譯,得到 Example.dll
2, 打開(kāi) Command,cd 到 Example.dll 所在目錄,輸入 Python2,進(jìn)入python環(huán)境
>>> from ctypes import * >>> dll = CDLL("Example.dll") >>> print dll.getInt() 5 >>> getStr = dll.getString >>> getStr.restype = c_char_p >>> pChar = getStr() >>> print c_char_p(pChar).value hello >>> setStr = dll.setString >>> setStr.argtypes = [c_char_p] >>> pStr = create_string_buffer("hello") >>> setStr(pStr) hello -1043503984
總結(jié)
以上所述是小編給大家介紹的Windows系統(tǒng)Python直接調(diào)用C++ DLL的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
