PyArray_SimpleNewFrom中的分段错误

2024-04-18 01:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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;

}

Python代码:

^{pr2}$

详细输出:

check0
check1
check2
Segmentation fault (core dumped)

Tags: 代码py数组intpyobjectargvprintfpdict

热门问题