简体   繁体   中英

Strange behavior of extended C++ function

I'm writing Python wrapper for C++ function repeating_count::count(string str) . The algorithm of this function isn't important, but it always return int . My wrapper gets list[str] as input and returns list[int] . The code of my wrapper is below:

PyObject* count_rep_list(PyObject *mod, PyObject *args){
    PyObject* inputList = PyList_GetItem(args, 0);
    PyObject* outputList = PyList_New(0);
    cout << PyList_Size(inputList);
    char* str;
    for(size_t i = 0; i < PyList_Size(inputList); ++i){
        PyObject* list_item = PyList_GetItem(inputList, i);
        if(!PyArg_Parse(list_item, "s", &str)){
            return NULL;
        }
        PyList_Append(outputList, PyLong_FromSize_t(repeating_count::count(string(str))));
    }
    return outputList;
}

Then I made a python module with this function:

PyMODINIT_FUNC PyInit_repeating_count() {
    static PyMethodDef ModuleMethods[] = {
            {"count_rep_list", count_rep_list, METH_VARARGS, "counting repeatings for list of strings"},
            { NULL, NULL, 0, NULL}
    };
    static PyModuleDef ModuleDef = {
            PyModuleDef_HEAD_INIT,
            "repeating_count",
            "counting repeatings",
            -1, ModuleMethods,
            NULL, NULL, NULL, NULL
    };
    PyObject * module = PyModule_Create(&ModuleDef);
    return module;
}

I successfully compiled and linked this module in .so file. But when I want to call the function from Python 3, I catch

Segmentation fault (core dumped)

So, what I'm doing wrong?

The fragment of Python code for calling count() :

from repeating_count import *
print(count_rep_list(["sdfsf", "sf", "sdfvgsdgsd"]))

I solved my issue. There was simply an error in code.

I had to use PyTuble_GetItem(args, 0) instead of PyList_GetItem(args, 0) beacuse args is a tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM