将数组/元组从python传递回C ++ [英] Passing array/tuple from python back to c++

查看:425
本文介绍了将数组/元组从python传递回C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将列表从cpp传递给python并将其取回.最初,我尝试传递一个值并获取一个值.有效.现在,我试图传递完整的数组/列表,下面是我的cpp代码:

I am trying to pass a list to python from cpp and taking it back. Initially I tried to pass a single value and get back one value. It worked. Now I am trying to pass the complete array/list Below is my cpp code:

#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;
}   

我总是收到失败.. !!".

I am always getting "FAILED..!!".

这是我的mytest.py

Here is my mytest.py

def stuff(a):
   x=a
   return x

有什么建议可以解决我的问题吗?

Any suggestions where I might be going wrong?

推荐答案

来自

PyObject * PyObject_CallObject(PyObject *可调用,PyObject * args)
这等效于Python表达式:callable(* args).

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)
这等效于Python表达式:callable(arg1,arg2,...).

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

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

So change your call to the following:

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

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

(or you could wrap your list inside another list and keep on using CallObject, but this is by far the easier solution)

这篇关于将数组/元组从python传递回C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆