環(huán)境:Window 10,VS 2019, Python 2.7.12, 64bit
1,打開 VS 2019,新建C++ Windows 動態(tài)鏈接庫工程 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
#include
using 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, 打開 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的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

