我从C ++函数调用Python函数,如下所示。
void CPPFunction(PyObject* pValue)
{
...
pValue = PyObject_CallObject(PythonFunction, NULL);
...
}
int main()
{
PyObject *pValue = NULL;
CPPFunction(PValue);
int result_of_python_function = Pylong_aslong(PValue);
}
我想在CPPFunction之外访问python函数的返回值。由于PyObject_CallObject返回的PObject *的范围在CPPFunction内,如何访问CPPFunction外的值?
答案 0 :(得分:1)
像在其他地方一样从函数返回它。
PyObject* CPPFunction()
{
// ...
PyObject* pValue = PyObject_CallObject(PythonFunction, NULL);
// ...
return pValue;
}
int main()
{
PyObject *value = CPPFunction();
int result_of_python_function = Pylong_aslong(value);
}
答案 1 :(得分:0)
进行以下更改,你可以访问CPPFunction以外的python函数的返回值。希望这有助于:
PyObject* CPPFunction(PyObject* PythonFunction) // changes return type from void to PyObject and pass PythonFunction to be called
{
pValue = PyObject_CallObject(PythonFunction, NULL);
return pValue;
}
int main()
{
PyObject *pValue = NULL;
pValue = CPPFunction(PythonFunction); // assign return value from CPPFunction call to PyObject pointer pvalue
long int result_of_python_function = Pylong_aslong(PValue);// data type changed from int to long int
cout << result_of_python_function << endl; // just printing the python result
}