python嵌入:将列表从C传递到python函数 [英] python embedding: passing list from C to python function

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

问题描述

尝试从C ++将列表传递给python无效.这是相关的代码(使用其他相关的帖子编写):

Trying to pass a list to python from C++ is not working. Here is the relevant code ( written using other related postings):

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

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

// 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, "mysolve");

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

PyObject *l = PyList_New(xvarcount);
for(size_t i=0; i<xvarcount; i++){
  pValue = PyInt_FromLong(0);
  PyList_SetItem(l, i, pValue);
}

PyObject *arglist = Py_BuildValue("(o)", l);
pValue = PyObject_CallObject(pFunc, arglist);

Python脚本MySolver.py是:

The python script MySolver.py is:

def mysolve(vals):
    print vals
    return 0

我正在按照其他地方的建议进行操作. mysolve函数只是不会被调用,而C ++程序会继续前进,而不会在PyObject_CallObject函数调用时报告任何错误. 请注意,如果我将单个参数作为元组传递给我的Solve函数,则代码可以正常工作.但是带有列表,它不起作用.有什么想法,为什么它不起作用?

I am doing everything as suggested elsewhere. mysolve function just does not get called and the C++ program just proceeds forward without reporting any error at the PyObject_CallObject function call. Note that the code works fine, if I pass a single argument as a tuple to the my solve function. But with a list it is not working. Any ideas, why it is not working?

推荐答案

使用Py_BuildValue是错误的.网络上此方法的文档,例如 http://docs.python.org/release/1.5.2p2/ext /buildValue.html 具有此错字,这就是为什么我使用小o而不是大写O的原因.正确的调用是: Py_BuildValue('(O)',l)

Usage of Py_BuildValue was erroneous. The documentation of this method on the web e.g. http://docs.python.org/release/1.5.2p2/ext/buildValue.html has this typo, which is why I used small o instead of capitalized O. The correct call is: Py_BuildValue('(O)', l)

这篇关于python嵌入:将列表从C传递到python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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