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

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

问题描述

我想从 C++ 代码中返回一些数据作为 numpy.array 对象.我查看了 boost::python::numeric,但它的文档非常简洁.我可以举个例子吗?返回一个(不是很大)vector 到 python?我不介意复制数据.

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.

推荐答案

更新: 在我的原始答案中描述的库 (https://github.com/ndarray/Boost.NumPy) 自 Boost 1.63 起已直接集成到 Boost.Python 中,因此独立版本现已弃用.下面的文本现在对应于新的集成版本(只有命名空间发生了变化).

UPDATE: the library described in my original answer (https://github.com/ndarray/Boost.NumPy) has been integrated directly into Boost.Python as of Boost 1.63, and hence the standalone version is now deprecated. The text below now corresponds to the new, integrated version (only the namespace has changed).

Boost.Python 现在将 NumPy C-API 的中等完整包装器包含到 Boost.Python 接口中.这是相当低级的,主要集中在如何解决更困难的问题,即如何在不复制的情况下将 C++ 数据传入和传出 NumPy,但这里是你如何使用复制的 std::vector 返回:

Boost.Python now includes a moderately complete wrapper of the NumPy C-API into a Boost.Python interface. 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/python/numpy.hpp"

namespace bp = boost::python;
namespace bn = boost::python::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::python 返回 numpy.array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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