1

I want to use boost::python to wrap a function returning the python value

array(28.4)

of type

numpy.ndarray

I haven't been able to extract this value to a c++ type. Here is what I have come up with so far (and the results):

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

: 0-d arrays can't be indexed

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

: No registered converter was able to produce a C++ rvalue of type double from this Python object of type numpy.ndarray

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

: No registered converter was able to extract a C++ pointer to type void * __ptr64 from this Python object of type numpy.ndarray

One would hope, that the standard hack in the last version would work - but it doesn't. Neither does any std:: type I have tried so far, such as vector.

Any ideas?

1 Answer 1

3

maybe this will help:

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

Please note that this is untested code and doesn't come with a warranty.

Cheers
Ben

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help. However, in my boost 1_58_0 distribution there is no boost/numpy.h header. Is this not part of the boost library?
Oh, boost::numpy is not part of the main distribution. It's located at github.com/ndarray/Boost.NumPy Get it with git clone github.com/ndarray/Boost.NumPy.git

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.