SWIG返回PyObject作为python对象吗? [英] SWIG return PyObject as python object?

查看:467
本文介绍了SWIG返回PyObject作为python对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个SWIG封装的类,它处理指向某些数据的指针,如下面的代码所示.我想从数据构造一个numpy ndarray对象,并将其返回给用户.我希望它使用数据作为缓冲区,但不占用所有权.如果我是对的,我将使用numpy C ++ api PyArray_SimpleNewFromData.但是,我的问题是如何将其返回给python?如果我编写以下get函数,SWIG会自动将其作为python对象返回吗?如果没有,我该怎么办?

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

顺便说一句,我也在努力寻找上述api的头文件和库文件.如果您知道,也请告诉我.谢谢.

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.

更新:

我尝试过SWIG封装此类.其他一切都很好,除了当我在python中调用get函数(如下所示)时,我遇到了段错误.感谢您的帮助.

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()

更新2:

似乎PyArray_SimpleNewFromData是已弃用的函数.那么这是否仍然受支持,或者还有其他推荐的方法吗?

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?

推荐答案

我在swig中使用typemap找出了解决方案:

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

这篇关于SWIG返回PyObject作为python对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆