Python在返回C ++映射值时崩溃

时间:2018-06-26 11:37:01

标签: python c++ python-c-api python-extensions

我正在编写一个Test以将数据保留在C ++映射中。我正在使用Python C-Api。
添加int值并获取地图的长度没问题。
但是,当我从地图上获取一个值并将其返回给Python时,解释器会崩溃。 这是我的代码:

    //some includes 
    int VerboseLog = 99;
    typedef map<const char*, int> SessionKeeper;
    static SessionKeeper openSessions;

    static PyObject* getSession(PyObject* self, PyObject* args) {
        cout << "get" << endl;
        const char *key;

        if (!PyArg_ParseTuple(args, "z*", &key)) {
            PyErr_SetString(PyExc_Exception, "UUID konnte nicht ausgelesen werden");
            PyErr_PrintEx(1);
            return NULL;
        }

        int r = openSessions.at(key);
        return Py_BuildValue("i", r);
    }

    static PyObject *addSession(PyObject* self, PyObject* args) {
        cout << "Hello" << endl;
        const char  *key;
        int toAppend;

        if (!PyArg_ParseTuple(args, "si", &key, &toAppend)) {
            PyErr_SetString(PyExc_Exception, "Ein Parameter konnte nicht ausgelesen werden");
            PyErr_PrintEx(1);
            return NULL;
        }

        openSessions[key] = toAppend;
        cout << openSessions.size() << endl;
        cout << openSessions[key] << endl;
        Py_RETURN_NONE;
    }

    static PyObject* length(PyObject *self){
        cout << "length: ";
        int i = openSessions.size();
        return Py_BuildValue("i",i);
    }

    static PyMethodDef SessionKeeper_methods[] = {
        /*Note the third entry (METH_VARARGS). This is a flag telling the interpreter the calling convention
        to be used for the C function. It should normally always be METH_VARARGS or METH_VARARGS | METH_KEYWORDS;
        a value of 0 means that an obsolete variant of PyArg_ParseTuple() is used.*/
        { "length", (PyCFunction)length, METH_VARARGS, "return length of a Session" },
        { "addSession", (PyCFunction)addSession, METH_VARARGS, "add a Session." },
        { "getSession", (PyCFunction)getSession, METH_VARARGS, "get a Session" },
        { NULL }
    };

    static PyModuleDef sessionKeeperMod = {
        PyModuleDef_HEAD_INIT,
        u8"SessionKeeper",
        NULL,
        -1,
        SessionKeeper_methods
    };

    static PyModuleDef CpluplusModules_ModDef = {
        PyModuleDef_HEAD_INIT,
        u8"CPlusPlusMouldes",
        u8"Enthält alle Erweietrungen",
        -1,
        NULL, NULL, NULL, NULL, NULL
    };

    PyMODINIT_FUNC PyInit_CPlusPlusModules(void) {
            PyObject* m, *sessionMod;

            if (PyType_Ready(&TAModulType) < 0)
                return NULL;

            if (PyType_Ready(&DatabaseReader_Type) < 0)
                return NULL;

            if (!(sessionMod = PyModule_Create(&sessionKeeperMod))) {
                cout << "fail" << endl;
                return NULL;
            }

            m = PyModule_Create(&CpluplusModules_ModDef);
            if (m == NULL)
                return NULL;

            Py_INCREF(&TAModulType);
            Py_INCREF(&DatabaseReader_Type);

            PyModule_AddObject(m, "TAModul", (PyObject *)&TAModulType);
            PyModule_AddObject(m, "DBReader", (PyObject *)&DatabaseReader_Type);
            PyModule_AddObject(m, "SessionKeeper", sessionMod);

            return m;
    }

其他模块(DBReader和TAModule)可以正常工作。目标将是确保地图中的PythonObjects安全(包含DbReader对象和TAModul对象)。

但是我想问为什么getSession在返回时使Interpreter崩溃?以及为什么length函数能正常工作。

1 个答案:

答案 0 :(得分:0)

map<const char*,...>match based on the address of the string rather than the contents。因此,at很可能会失败并抛出C ++ out_of_range异常。

您应该从换行开始

int r = openSessions.at(key);

带有try {} catch块,以阻止通过Python解释器(不是C ++,因此无法处理)传播的out_of_range异常。

然后应该更改映射以匹配字符串内容上的键。最简单的方法是使用map<std::string,int>