如何复制 PyObject*?

How to Copy PyObject*?

我正在从 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 函数的 return 值。由于 PyObject_CallObject 编辑的 PObject* return 的范围在 CPPFunction 内,如何访问 CPPFunction 之外的值?

Return 就像在其他任何地方一样从函数中获取它。

PyObject* CPPFunction()
{
    // ...
    PyObject* pValue = PyObject_CallObject(PythonFunction, NULL);
    // ...
    return pValue;
}

int main()
{
  PyObject *value = CPPFunction();
  int result_of_python_function = Pylong_aslong(value);
}

进行以下更改,您可以在 CPPFunction.Hope 之外访问 python 函数的 return 值,这有助于:

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
}