Windows系统Python直接调用C++ DLL的方法
环境:Window10,VS2019,Python2.7.12,64bit
1,打开VS2019,新建C++Windows动态链接库工程Example,加入下列文件,如果Python是64位的则在VS中Solutionplatforms选择x64编译成64位的DLL;
Example.h
#pragmaonce #ifndefCPP_EXPORTS #defineCPP_EXPORTS #endif #ifdefCPP_EXPORTS #defineCPP_API_declspec(dllexport) #else #defineCPP_API_declspec(dllimport) #endif #includeusingnamespacestd; #ifdef__cplusplus extern"C" { #endif CPP_APIint__cdeclgetInt(); CPP_APIconstchar*__cdeclgetString(); CPP_APIvoid__cdeclsetString(constchar*str); #ifdef__cplusplus } #endif
Example.cpp
#include"pch.h"
#include"Example.h"
CPP_APIint__cdeclgetInt()
{
return5;
}
CPP_APIconstchar*__cdeclgetString()
{
return"hello";
}
CPP_APIvoid__cdeclsetString(constchar*str)
{
cout<
编译,得到Example.dll
2,打开Command,cd到Example.dll所在目录,输入Python2,进入python环境
>>>fromctypesimport*
>>>dll=CDLL("Example.dll")
>>>printdll.getInt()
5
>>>getStr=dll.getString
>>>getStr.restype=c_char_p
>>>pChar=getStr()
>>>printc_char_p(pChar).value
hello
>>>setStr=dll.setString
>>>setStr.argtypes=[c_char_p]
>>>pStr=create_string_buffer("hello")
>>>setStr(pStr)
hello
-1043503984
总结
以上所述是小编给大家介绍的Windows系统Python直接调用C++DLL的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!