C++调用Python-4:调用Python函数,传参数字

 

# 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;
}

 

posted @ 2022-04-02 17:27  十一的杂文录  阅读(95)  评论(0编辑  收藏  举报