I want to access some python functions that I wrote from my C code. One of my python functions receives a numpy array as an input. In my C code, this array is allocated in the dynamic memory. Whenever my python function is called I receive a segmentation fault, and I am not sure what am I doing wrong. I tried to pass N, O, O& to the Py_BuildValue function, but I keep on getting the same result.
Here is the python simplified code.
#Python simple function that receives pointer to array
#!/usr/bin/python3
import numpy as np
def getNumpyArrayPointer(pointer):
data = np.ctypeslib.as_array(pointer, shape=(1000,1)).astype(np.int32) #Doesn't matter if I comment out this line. Fault continues
print('Python function getNumpyArrayPointer() called')
return data
Here is the C simplified code
#include <iostream>
#include <Python.h>
#include "pyhelper.h"
int capitest()
{
Py_Initialize();
PyObject* sysPath = PySys_GetObject((char*)"path");
PyObject* programName = PyUnicode_FromString("path-to-python-script");
PyList_Append(sysPath, programName);
Py_DECREF(programName);
PyObject* pName = PyUnicode_FromString("python-script-name");
PyObject* pModule = PyImport_Import(pName);
PyObject* pValue;
CPyObject pFunc;
PyObject* args;
if(pModule)
{
pFunc = PyObject_GetAttrString(pModule, "getNumpyArrayPointer");
uint32_t *array = (uint32_t *)malloc (1000);
args = Py_BuildValue("(N)", array );
if(pFunc && PyCallable_Check(pFunc))
{
printf("Calling getNumpyArrayPointer\n");
pValue = PyObject_CallObject(pFunc, args);
Py_DECREF(args);
printf("Called getNumpyArrayPointer\n");
if (PyErr_Occurred())
{
PyErr_Print();
return 0;
}
}
else
{
printf("ERROR: function getNumpyArrayPointer()\n");
}
}
else
{
printf("ERROR: Module not imported\n");
}
Py_Finalize();
return 0;
}
int main()
{
capitest();
}
Output:
Calling getNumpyArrayPointer
Segmentation fault (core dumped)