# mytest.py def myadd(a, b): print("this is test python print add function") return a+b
#include "Python.h" #include <iostream> using namespace std; int main(int argc, char* argv[]) { Py_Initialize(); if (!Py_IsInitialized()) { cout << "初始化失败" << endl; } PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); PyObject* pModel = nullptr; pModel = PyImport_ImportModule("mytest"); // add 函数 PyObject* addFunc = PyObject_GetAttrString(pModel, "myadd"); PyObject* addArgs = Py_BuildValue("ii", 13, 58); PyObject* addRes = PyObject_CallObject(addFunc, addArgs); int res = PyLong_AsLong(addRes); cout << "返回值:" << res << endl; Py_DecRef(addRes); Py_DecRef(addArgs); Py_DecRef(addFunc); Py_Finalize(); return 0; }