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

我正在尝试将一个列表从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

任何建议,我可能会出错的地方?


幕布斯7119047
浏览 137回答 1
1回答

函数式编程

从文档中:PyObject* PyObject_CallObject(PyObject *callable, PyObject *args)这相当于 Python 表达式:callable(*args)。而 记录为:PyObject_CallFunctionObjArgsPyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL)这相当于 Python 表达式:callable(arg1, arg2, ...)。因此,请将您的呼叫更改为以下内容:PyObject*&nbsp;result&nbsp;=&nbsp;PyObject_CallFunctionObjArgs(pFunc,&nbsp;list,&nbsp;NULL);(或者您可以将列表包装在另一个列表中并继续使用,但这是迄今为止更简单的解决方案)CallObject
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python