I am trying to do some Python wrapping to use custom C++ stuff. The main type we use is a 2D gray image type with data allocated in a 1D buffer. I try to wrap it this way (following an example in an ubuntu forum):
PyObject* to_python_object(const custom2DImage& img) {
int type_num = (int)NPY_UBYTE;
long int dims[2] = {img.nr(), img.nc()};
uchar** tmp_img = new uchar*[img.nr()];
tmp_img[0] = new uchar[img.nr() * img.nc()];
for (int i = 1; i < img.nr(); ++i)
tmp_img[i] = tmp_img[0] + img.nc();
for (int i = 0; i < img.nc(); ++i)
memcpy(tmp_mat[i], &img(i, 0), img.nc() * sizeof(uchar));
PyObject* py_img = PyArray_SimpleNewFromData(2, dims, type_num, tmp_img[0]);
Py_INCREF(py_img);
delete[] tmp_img[0];
delete[] tmp_img;
PyObject *repr = PyObject_Repr(py_img);
const char *s = PyString_AsString(repr);
cout << s << endl;
Py_XDECREF(repr);
return py_img;
}
My Python object representation from the C++ function is ok but as soon as I try to print it in my python main, it segfault (even though the shape is good). The Python code is as follow:
img = cst.read_image(filename);
if img is None:
print("Can not load image from", filename)
sys.exit(-1)
print(img)
Do you have an idea why do I have this issue ?