【问题标题】:calling python function with parameters from C++使用 C++ 中的参数调用 python 函数
【发布时间】:2014-06-23 11:54:19
【问题描述】:

我创建了嵌入式 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

【问题讨论】:

  • 有一个明显的错误:而不是success(指针类型)我将字符串转换fc的结果传递给successfull。我是个白痴,我没有注意到:P

标签: python c++


【解决方案1】:

这是来自 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);

在我看来,您应该注意引用计数。

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

这里讨论分段错误。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    相关资源
    最近更新 更多