3

我希望使用 C-API 将数组从 C++ 传递到 Python。通过查看这里的各种主题,我知道我应该使用 PyArray_SimpleNewFromData 方法。当我试图在一个非常小的数组上实现时,我的代码中出现了我无法检测到的分段错误。谁能帮我解决这个问题?

C++ 代码:

void init_numpy()
{
    import_array(); 
}
int main(int argc, char *argv[])
{
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs, *pXVec, *xarr1;
PyObject *c ;
PyObject *pValue1 ;
int fArray[2] = {10,1} ;
PyObject *p = NULL ;
npy_intp m1 = 2;
Py_Initialize();
PySys_SetArgv(argc, argv); 
init_numpy();
pName = PyString_FromString(argv[1]);
pModule = PyImport_Import(pName);
printf("check0\n");
pDict = PyModule_GetDict(pModule);
printf("check1\n");
pFunc = PyDict_GetItemString(pDict, argv[2]);
printf("check2\n");
c = PyArray_SimpleNewFromData(1,&m1,NPY_INT,fArray);
printf("check3\n");
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0,c);    
pValue = PyObject_CallObject(pFunc, pArgs);
if (pArgs != NULL)
{
   Py_DECREF(pArgs);
}
// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);

// Finish the Python Interpreter
Py_Finalize();

return 0;

}

蟒蛇代码:

import numpy as np
import scipy.io

def main(a): 
    print a

详细输出:

check0
check1
check2
Segmentation fault (core dumped)
4

0 回答 0