SWIG return PyObject as python object?

别等时光非礼了梦想. 提交于 2020-01-03 05:24:31

问题


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?


回答1:


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_;
};


来源:https://stackoverflow.com/questions/28425484/swig-return-pyobject-as-python-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!