Segmentation fault in PyArray_SimpleNewFromData

2019-02-19 03:38发布

问题:

I am looking to pass an array from C++ to Python using C-API. By looking at various topics here, I came to know that I should be using PyArray_SimpleNewFromData method. When I am trying to implement on a very small array, I am getiing a segmentation fault in my code which I am not able to detect. Can anyone help me with this issue?

C++ code :

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 Code:

import numpy as np
import scipy.io

def main(a): 
    print a

Output on verbose :

check0
check1
check2
Segmentation fault (core dumped)