1

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 ?

1 Answer 1

1

Ok so I thought the PyArray_SimpleNewFromData function was copying data but it seems it doesn't. My mistake was to free the tmp_img 2D array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.