将数组/元组从python传回c ++

问题描述 投票:0回答:1

我正在尝试将列表从cpp传递给python并取回。最初,我尝试传递一个值并返回一个值。有效。现在,我试图传递完整的数组/列表,下面是我的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;
}   

我总是收到“失败.. !!”。

这是我的mytest.py

def stuff(a):
   x=a
   return x

关于我可能要去哪里的任何建议?

python c++ linker python-embedding
1个回答
0
投票

来自the documentation

PyObject * PyObject_CallObject(PyObject * callable,PyObject * args)这等效于Python表达式:callable(* args)。

PyObject_CallFunctionObjArgs记录为:

PyObject * PyObject_CallFunctionObjArgs(PyObject * callable,...,NULL)这等效于Python表达式:callable(arg1,arg2,...)。

因此将您的呼叫更改为以下内容:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.