Note:测试Python 需要先编译一下DLL
内容:
C++调用python脚本
python脚本调用C++ DLL/SO
-----------------------------------------------------割割割割割割-----------------------------------------------------------
C++调用python脚本 :
Q1:安装Python:
note:
注意x86和x64平台,根据计算机类型选择,否则会报平台不兼容问题.
必须勾选DownLoad Debug Binaries
否则必然会报link1104 找不到phthon3_d.lib
Q2:C++工程配置:
Note:必须把DLL放到项目根目录去(是项目根路径,不是解决方案根路径),否则运行 会报找不到Python.dll 错误
Q3:代码:
逻辑:C++生成一个Python类,并调用成员方法.返回结果。
.py部分:
classmath:def __init__(self):
self.test= ''
defadd(self, num1, num2):print(self)print ("add functin start:", self.test)print (num1 +num2)print ("add functin end:<", self.test + ">")return num1 +num2defsubtract(self, num1, num2):print(self)print ("sub functin :")print (num1 -num2)return num1 - num2
.cpp部分:
//CppCallPython.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。//#include"pch.h"#include#include"Python.h"
using namespacestd;intmain()
{
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");if (!Py_IsInitialized())
{
printf("初始化失败!");return 0;
}
PyObject* pModule =NULL;
PyObject* pFunc =NULL;
PyObject* pDict =NULL;
PyObject* pClass =NULL;
PyObject* pIns =NULL;
pModule= PyImport_ImportModule("hello");
assert(pModule!=NULL);
pDict=PyModule_GetDict(pModule);
assert(pDict!=NULL);
pClass= PyDict_GetItemString(pDict, "math");
assert(pClass!=NULL);
pIns=PyObject_CallObject(pClass, nullptr);
assert(pIns!=NULL);
auto result= PyObject_CallMethod(pIns, "add", "(ii)", 1, 2);//PyObject_New();
std::cout<< "";
Py_DECREF(pIns);
Py_Finalize();
std::cout<< "Hello World!\n";
}
-----------------------------------------------------割割割割割割-----------------------------------------------------------
python调用C++ DLL/SO :
Q1:关于本机调试:
如果希望debuger程序(C++ DLL),需要在VS python项目中启用本机代码调试:
QQ:完整代码:
c++ .cpp部分
using namespacestd;extern "C"{__declspec(dllexport)char* HiPython(char*msg);__declspec(dllexport)int HiPythonInt(intb);
}
char* HiPython(char*msg)
{
cout<< "[output on cpp] from python message :" << msg <
}
int HiPythonInt(intb)
{
cout<< "[output on cpp] from python message : 系数:"<< b <
}
Python 部分:
importsys, platformimportctypes, ctypes.utilfrom ctypes importcdll
lib=Noneif platform.system() == "Windows":print(f"hello python on Windows")
lib= cdll.LoadLibrary("./dll/cppdll.dll")elif platform.system() == "Linux":
lib= cdll.LoadLibrary("./so/cppdll.so")print(f"hello python on Linux")else:print(f"unknown platform.")if lib !=None:
lib.HiPython.argtypes=[ctypes.c_char_p]
lib.HiPython.restype=ctypes.c_char_p
teststr= bytes("i am 拆腻子","utf8")
ret_str= lib.HiPython(teststr).decode("utf8")
ret_int= lib.HiPythonInt(3);print("HiPythonInt return :", ret_int, "| HiPython Return:", ret_str)else:print("input any key and enter exit:")print("input any key and enter exit:")
input()