2015-06-05 26 views
1

价值我想使用boost ::蟒蛇来包装一个函数返回值蟒的boost :: python的提取物C++从numpy.ndarray返回值

array(28.4) 

numpy.ndarray 

我的天堂无法将此值提取到C++类型。以下是我想出了到目前为止(和结果):

double resultValue = python::extract<double>(result[0]); 

:0-d阵列不能被索引

double resultValue = python::extract<double>(result); 

:没有注册转换器能够从此类型的numpy生成一个类型为double的C++右值numpy.ndarray

void* resultValue = python::extract<void*>(result); 

:没有注册转换器能够提取的C++指针从类型numpy.ndarray

人们希望这个Python对象类型为void * __ptr64,在最后一个版本的标准黑客会工作 - 但事实并非如此。迄今为止,我还没有尝试任何std :: type,例如vector。

任何想法?

回答

2

也许这将帮助:

#include <boost/python.hpp> 
#include <boost/numpy.hpp> 

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

#define PY_ASSERT(expr) { if(!(expr)) { \ 
    PyErr_SetString(PyExc_TypeError, (boost::format("PY_ASSERT(%1%:%2%): !(%3%) '%4%'") % (__FILE__) % (__LINE__) % (expr) % (#expr)).str().c_str()); \ 
    bp::throw_error_already_set(); \ 
}; }; 

#define PY_ASSERT_EQUALS(a, b) { if((a) != (b)) { \ 
    PyErr_SetString(PyExc_TypeError, (boost::format("PY_ASSERT_EQUALS(%1%:%2%): %3% != %4%") % (__FILE__) % (__LINE__) % (a) % (b)).str().c_str()); \ 
    bp::throw_error_already_set(); \ 
}; }; 

.... 

auto ret_ext = bp::extract<bn::ndarray>(result); 
PY_ASSERT(ret_ext.check()); 

const bn::ndarray& ret = ret_ext(); 
PY_ASSERT(bn::equivalent(ret.get_dtype(), bn::dtype::get_builtin<double>())); 
PY_ASSERT_EQUALS(ret.get_nd(), 1); 
PY_ASSERT_EQUALS(ret.shape(0), 1); 

double resultValue = *reinterpret_cast<double*>(mean.get_data()); 

请注意,这是未经测试的代码,并没有附带保修。

干杯

+0

感谢您的帮助。但是,在我的boost 1_58_0版本中,没有boost/numpy.h头文件。这不是助推库的一部分吗? – user1934212

+0

哦,boost :: numpy不是主要发行版的一部分。它位于https://github.com/ndarray/Boost.NumPy 得到它与 ** git克隆https://github.com/ndarray/Boost.NumPy.git** – bensch128