# mytest.py def myjoin(a, b): print("num a + str b") return f"{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, "myjoin"); PyObject* addArgs = Py_BuildValue("(is)", 12, "34"); PyObject* addRes = PyObject_CallObject(addFunc, addArgs); char* s = nullptr; PyArg_Parse(addRes, "s", &s); cout << "返回值:" << s << endl; Py_DecRef(addRes); Py_DecRef(addArgs); Py_DecRef(addFunc); Py_Finalize(); return 0; }