如何复制 PyObject*

How to Copy PyObject*?

本文关键字:PyObject 复制 何复制      更新时间:2023-10-16

我正在从如下所示的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之外访问该值?

像在其他任何地方一样从函数中返回它。

PyObject* CPPFunction()
{
    // ...
    PyObject* pValue = PyObject_CallObject(PythonFunction, NULL);
    // ...
    return pValue;
}
int main()
{
  PyObject *value = CPPFunction();
  int result_of_python_function = Pylong_aslong(value);
}

进行以下更改,您可以在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
}