0

Suppose I have a SWIG-wrapped class taking care of a pointer to some data, as shown in the following code. I would like to construct a numpy ndarray object from the data and return it to the user. I want it to use the data as it's buffer but not take the ownership. If I'm right, I shall use the numpy C++ api PyArray_SimpleNewFromData. However, my question is how do I return this to python? If I write the following get function, will SWIG automatically return it as a python object? If not, what shall I do?

class Test {
 public:
  Test () { ptr_ = new uint8_t[200]; }
  ~Test() { delete [] ptr_; }

  PyObject* get() {
    npy_intp dims[1] = {25};
    return PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, ptr_);
  }

 private:
  uint8_t* ptr_;
};

By the way, I'm also struggling in finding the header files and library files for the above api. If you know please also tell me. Thanks.

UPDATE:

I tried SWIG wrap this class. Everything else works good, except when I call the get function in python (like the following), I got segmentation fault. Any help is appreciated.

x = Test()
y = x.get()

UPDATE 2:

It seems that PyArray_SimpleNewFromData is a deprecated function. So is this still supported or is there any other more recommended way of doing this?

shaoyl85
  • 1,854
  • 18
  • 30

1 Answers1

0

I figured out the solution using typemap in swig:

%typemap(out) double* {
  npy_intp dims[1] = {25};
  $result = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, $1);
}

class Test {
 public:
  Test () { ptr_ = new uint8_t[200]; }
  ~Test() { delete [] ptr_; }

  double* get() {
    return (double*) ptr_;
  }

 private:
  uint8_t* ptr_;
};
shaoyl85
  • 1,854
  • 18
  • 30