吐槽:爬坑ing,CSDN害人不浅.都是些什么沙雕接入教程,还如自己看文档
python3 api 文档: https://docs.python.org/3/library/
栗子工程,github:https://github.com/linqingwudiv1/CppCallPythonExample
-----------------------------------------------------割割割-----------------------------------------------------------
Q1:安装Python:
下载地址:https://www.python.org/downloads/windows/
note:
注意x86和x64平台,根据计算机类型选择,否则会报平台不兼容问题.
必须勾选DownLoad Debug Binaries
否则必然会报link1104 找不到phthon3_d.lib
Q2:C++工程配置:
Note:必须把DLL放到项目根目录去(是项目根路径,不是解决方案根路径),否则运行 会报找不到Python.dll 错误
Q3:代码:
逻辑:C++生成一个Python类,并调用成员方法.返回结果。
.py部分:
class math: def __init__(self): self.test = '<test>' def add(self, num1, num2): print (self) print ("add functin start:", self.test) print (num1 + num2) print ("add functin end:<", self.test + ">") return num1 + num2 def subtract(self, num1, num2): print (self) print ("sub functin :") print (num1 - num2) return num1 - num2
.cpp部分:
// CppCallPython.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include "Python.h" using namespace std; int main() { 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 << "<finished>"; Py_DECREF(pIns); Py_Finalize(); std::cout << "Hello World!\n"; }