如何从boost ::蟒蛇返回numpy.array? [英] how to return numpy.array from boost::python?

查看:586
本文介绍了如何从boost ::蟒蛇返回numpy.array?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从C ++ code作为 numpy.array 对象返回一些数据。我有一个看看的boost ::蟒蛇::数字,但它的文档是很简洁。我可以得到例如一个例子返回一个(不是非常大)矢量<&双GT; 来蟒蛇?我不介意做数据的副本。

I would like to return some data from c++ code as a numpy.array object. I had a look at boost::python::numeric, but its documentation is very terse. Can I get an example of e.g. returning a (not very large) vector<double> to python? I don't mind doing copies of data.

推荐答案

Boost.Python的和numpy的之间的另一个接口可以在这里找到:

Another interface between Boost.Python and NumPy can be found here:

https://github.com/ndarray/Boost.NumPy

这是numpy的C-API的适度包装完全进入Boost.Python的接口,具有最终在提交提振的意图。我不知道该文档是比任何刺激更好的整体::蟒蛇::数字在这一点上,但也有很多code的例子和至少是正在积极发展。这是pretty低的水平,并主要集中在如何解决如何通过C ++数据和从numpy的不复制比较困难的问题,但这里是你如何做一个复制的std :: vector的回报与:

It's a moderately complete wrapper of the NumPy C-API into a Boost.Python interface, with the intention of eventually submitting it to Boost. I'm not sure the documentation is any better overall than boost::python::numeric at this point, but there are a lot of code examples and at least it's under active development. It's pretty low-level, and mostly focused on how to address the more difficult problem of how to pass C++ data to and from NumPy without copying, but here's how you'd do a copied std::vector return with that:

#include "boost/numpy.hpp"

namespace bp = boost::python;
namespace bn = boost::numpy;

std::vector<double> myfunc(...);

bn::ndarray mywrapper(...) {
    std::vector<double> v = myfunc(...);
    Py_intptr_t shape[1] = { v.size() };
    bn::ndarray result = bn::zeros(1, shape, bn::dtype::get_builtin<double>());
    std::copy(v.begin(), v.end(), reinterpret_cast<double*>(result.get_data()));
    return result;
}

BOOST_PYTHON_MODULE(example) {
    bn::initialize();
    bp::def("myfunc", mywrapper);
}

这篇关于如何从boost ::蟒蛇返回numpy.array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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