2015-09-12 119 views
0

我正在爲C++函數repeating_count::count(string str)編寫Python包裝。這個函數的算法並不重要,但它總是返回int。 我的包裝獲取list[str]作爲輸入並返回list[int]。我的包裝的代碼如下:擴展C++函數的奇怪行爲

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; 
} 

然後我做了這個功能的Python模塊:

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; 
} 

我成功編譯和.so文件鏈接這個模塊。但是,當我想從Python 3中調用該函數,我抓住

所以,我在做什麼錯

分割故障(核心轉儲)?

的Python代碼片段調用count()

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

str是一個單元化的指針,你傳遞給PyArg_Parse –

+0

@KennyOstrom,非常感謝。我已更正了代碼。 – VeLKerr

回答

0

我解決我的問題。代碼中只有一個錯誤。我不得不使用PyTuble_GetItem(args, 0)而不是PyList_GetItem(args, 0)因爲args是元組。