异常退出失败,使用c ++调用python脚本

时间:2012-05-03 03:16:46

标签: c++ python

当我的exe在python脚本完成后退出时,我得到一个错误指向 crt0dat.c enter image description here 这样的调用栈...... enter image description here 我的c ++代码或python代码中是否有错误?

像这样的c ++代码:

void PythonCall::call(std::vector<double>& s,std::vector<double>& b,std::vector<double>& t,std::vector<double>& y)
{

    PyObject* args = PyTuple_New(2);
    PyObject* tPyList = convert2PythonList(t);
    PyObject* yPyList = convert2PythonList(y);
    PyTuple_SetItem(args,0,tPyList);
    PyTuple_SetItem(args,1,yPyList);

    PyObject* r = PyObject_CallObject(func,args);

    PyObject* item;


    PyObject* iter = PyObject_GetIter(r);
    /*{
    PyObject *errtype, *errvalue, *traceback;
    PyErr_Fetch(&errtype, &errvalue, &traceback);
    PyObject *s = PyObject_Str(errvalue);
    char *errstr = PyString_AsString(s);
    std::cout << "Python Error: " << errstr; 
    }*/


    item = PyIter_Next(iter);
    int i = 0;
    PyObject* iter2 = PyObject_GetIter(item);
    PyObject* item2;
    while (item2 = PyIter_Next(iter2))
    {
        s[i] = PyFloat_AsDouble(item2);
        Py_XDECREF(item2);
        i++;
    }
    Py_XDECREF(item);
    //Py_XDECREF(iter2);

    item = PyIter_Next(iter);
    i = 0;
    iter2 = PyObject_GetIter(item);
    while (item2 = PyIter_Next(iter2))
    {
        b[i] = PyFloat_AsDouble(item2);
        Py_XDECREF(item2);
        i++;
    }
    Py_XDECREF(item);
    //Py_XDECREF(iter2);

    //Py_XDECREF(iter);
    Py_XDECREF(args);
    Py_XDECREF(r);
    Py_XDECREF(item);
    Py_XDECREF(tPyList);
    Py_XDECREF(yPyList);
    //std::cout << "done" << std::endl;
}

和python代码:

def get_slope_baseLine(tl,xl):
    slopes = get_slope2(tl,xl)
    baselines = get_leakTime(tl,slopes)
    return slopes,baselines
抱歉我的英语不好......

1 个答案:

答案 0 :(得分:3)

显然,您打算迭代两个列表并减少其元素的引用计数,但是您忘记重置iter,这样您就不会迭代第二个列表。

PyObject* iter = PyObject_GetIter(r);

item = PyIter_Next(iter);
int i = 0;
PyObject* iter2 = PyObject_GetIter(item);
PyObject* item2;
while (item2 = PyIter_Next(iter2))
{
    s[i] = PyFloat_AsDouble(item2);
    Py_XDECREF(item2);
    i++;
}
Py_XDECREF(item);

// ! Here you probably intended another call to PyObject_GetIter
item = PyIter_Next(iter);
i = 0;
iter2 = PyObject_GetIter(item);
while (item2 = PyIter_Next(iter2))
{
    b[i] = PyFloat_AsDouble(item2);
    Py_XDECREF(item2);
    i++;
}
Py_XDECREF(item);

然而,崩溃可能是由于其他原因(取决于您正在使用的功能的记录行为)。