使用C ++中的参数调用python函数

时间:2014-06-23 11:54:20

标签: python c++

我创建了一个调用函数的嵌入式python解释器,它有3个参数。我成功地设法为没有参数的函数执行此操作,但是当我执行PyObject_CallObject时,程序与SEGFAULT崩溃:

#0  0x00007ffff79c3a25 in PyEval_EvalCodeEx () from /usr/lib/libpython3.2mu.so.1.0
#1  0x00007ffff79c42bf in ?? () from /usr/lib/libpython3.2mu.so.1.0
#2  0x00007ffff79c730a in PyObject_Call () from /usr/lib/libpython3.2mu.so.1.0
#3  0x00000000004f3f31 in Huggle::Python::PythonScript::Hook_SpeedyFinished(Huggle::WikiEdit*, bool) ()

电话的源代码是:

void PythonScript::Hook_SpeedyFinished(WikiEdit *edit, bool successfull)
{
    if (edit == nullptr)
        return;
    if (this->ptr_Hook_SpeedyFinished != nullptr)
    {
        HUGGLE_DEBUG("Calling hook Hook_SpeedyFinished @" + this->Name, 2);
        // let's make a new list of params
        PyObject *args = PyTuple_New(3);
        PyObject *page_name = PyUnicode_FromString(edit->Page->PageName.toUtf8().data());
        PyObject *user_name = PyUnicode_FromString(edit->User->Username.toUtf8().data());
        PyObject *success;
        if (!successfull)
            successfull = PyUnicode_FromString("fail");
        else
            successfull = PyUnicode_FromString("success");
        if (PyTuple_SetItem(args, 0, page_name))
            HUGGLE_DEBUG("Failed to pass page_name to tuple @hook_speedy_finished", 3);
        if (PyTuple_SetItem(args, 1, user_name))
            HUGGLE_DEBUG("Failed to pass user to tuple @hook_speedy_finished", 3);
        if (PyTuple_SetItem(args, 2, success))
            HUGGLE_DEBUG("Failed to pass success to tuple @hook_speedy_finished", 3);
        PyObject_CallObject(this->ptr_Hook_SpeedyFinished, args);
        HUGGLE_DEBUG("finished", 1);
    }
}

此.cpp文件的完整源代码为https://github.com/huggle/huggle3-qt-lx/blob/master/huggle/pythonengine.cpp

有什么问题?这是调用函数的正确方法吗?我正在关注https://docs.python.org/3/c-api/object.htmlhttps://docs.python.org/2/c-api/tuple.html

1 个答案:

答案 0 :(得分:0)

以下是python文档中的一个示例。

PyObject *arglist;
...
arglist = Py_BuildValue("(l)", eventcode);
result = PyObject_CallObject(my_callback, arglist);
Py_DECREF(arglist);
if (result == NULL)
    return NULL; /* Pass error back */
/* Here maybe use the result */
Py_DECREF(result);

在我看来,你应该照顾refcount。

https://docs.python.org/3.0/extending/extending.html#calling-python-functions-from-c

此处讨论了分段错误。

Calling python method from C++ (or C) callback