python传入数组,将数组/元组从python传递回C ++

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

#include

#include

#include

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..!!".

Here is my mytest.py

def stuff(a):

x=a

return x

Any suggestions where I might be going wrong?

解决方案PyObject* PyObject_CallObject(PyObject *callable, PyObject *args)

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

Whereas PyObject_CallFunctionObjArgs is documented as:

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);

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值