我正在尝试从C ++调用python函数。但是,我不知道如何将参数传递给python函数调用。
我有一个名为“ arbName.py”的python文件和一个名为“ main.cpp”的c ++文件。
arbName.py
def someFunction(a):
return a
main.cpp
#include <Python.h>
int main()
{
Py_Initialize();
//add . to path
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
PyObject* myModuleString = PyUnicode_FromString((char*)"arbName");
PyObject* myModule = PyImport_Import(myModuleString);
PyObject* myFunction = PyObject_GetAttrString(myModule,(char*)"someFunction");
//couldn't figure out this part.
//How to declare a python variable and/or pass it to the python function.
PyObject* args = PyUnicode_FromString("1");
PyObject *myResult = PyObject_CallFunctionObjArgs(myFunction, args);
return 0;
}
编辑:我可以通过更改最后两行来实现
PyObject* args = Py_BuildValue("(d)", 2.0);
PyObject *myResult = PyObject_CallObject(myFunction, args);