将 array/tuple 从 python 传回 C++

Passing array/tuple from python back to c++

我正在尝试将列表从 cpp 传递到 python 并将其取回。最初我试图传递一个值并取回一个值。有效。现在我正在尝试传递完整的 array/list 以下是我的 cpp 代码:

#include <iostream>
#include <Python.h>
#include <numpy/arrayobject.h>
#include <typeinfo>
using namespace std;

int main()
{
Py_Initialize();
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyString_FromString("."));

PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;

// Build the name object
pName = PyString_FromString("mytest");

// Load the module object
pModule = PyImport_Import(pName);

// pDict is a borrowed reference 
pDict = PyModule_GetDict(pModule);

// pFunc is also a borrowed reference 
pFunc = PyObject_GetAttrString(pModule, "stuff");

if (!PyCallable_Check(pFunc))
  PyErr_Print();

PyObject *list = PyList_New (5);

Py_ssize_t size = PyList_GET_SIZE(list);

for(Py_ssize_t s = 0; s < size; s++ )
{
    PyList_SetItem(list, s, Py_BuildValue("d", 2.5));

}

PyObject* result = PyObject_CallObject(pFunc, list);
if(result==NULL)
{cout << "FAILED ..!!" << endl;}

cout << result << endl;;
return 0;
}   

我总是 "FAILED..!!"。

这是我的 mytest.py

def stuff(a):
   x=a
   return x

对我可能出错的地方有什么建议吗?

来自the documentation

PyObject* PyObject_CallObject(PyObject *callable, PyObject *args)
This is the equivalent of the Python expression: callable(*args).

PyObject_CallFunctionObjArgs 记录为:

PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL)
This is the equivalent of the Python expression: callable(arg1, arg2, ...).

所以将您的调用更改为以下内容:

PyObject* result = PyObject_CallFunctionObjArgs(pFunc, list, NULL);

(或者您可以将您的列表包裹在另一个列表中并继续使用 CallObject,但这是迄今为止更简单的解决方案)