I have the following class:
#include <array>
template<unsigned short D>
class Point {
private:
std::array<float, D> coordinates;
public:
Point() { for(int i=D-1; i>=0; --i) coordinates[i] = 0.0; }
Point(const Point& rhs) = default;
Point& operator=(const Point& rhs) = default;
~Point() = default;
float& get_ref(const unsigned short dimension)
{ return coordinates[dimension-1]; }
};
I’m trying to wrap it with:
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(fernpy) {
using namespace boost::python;
class_< Point<2> >("point")
.def("__call__", &Point<2>::get_ref, return_internal_reference<>());
}
I’m using gcc-4.7 to compile for boost 1.48, python-2.7 on Fedora 17. All the code is a file called testpy.cpp. I’m using these commands to compile:
g++ -std=c++11 -g -fPIC -I/usr/include/python2.7 -c testpy.cpp
g++ -shared -g -lpython2.7 -lboost_python -o libfern.so testpy.o
The compiler returns a bunch of boost internal errors, too many to post here. This excerpt seems to be the core of it. There are a bunch of “required from”s before it and “note”s after.
/usr/include/boost/python/object/make_instance.hpp:27:9: error: no matching function for call to ‘assertion_failed(mpl_::failed************ boost::mpl::or_<boost::is_class<float>, boost::is_union<float>, mpl_::bool_<false>, mpl_::bool_<false>, mpl_::bool_<false> >::************)’
It works just fine if I return a plain float from get_ref and remove the return_internal_reference<>() argument from the .def line of the wrapper. It’s weird because I’m doing the same thing with another, more complicated class template and it works just fine there too. I’ve been Googling and banging my head against this for almost a full day now. Anybody have any idea what the heck is going on?
UPDATE:
I ended up using the “getitem” and “setitem” special methods from python, a la this link. The link shows how to define a nifty struct template with static wrappers for access functions, so you don’t have to mess with the interface to your original C++ class.
From a python point-of-view,
floatsare an immutable-type. As such, python does not allow changing the value.For example, the following occurs in python:
Now, consider the following:
Thus,
boost::pythonprevents returning reference to types that will be immutable in python because Python does not support it.xdoes not store the value5; instead, it contains a reference to the5object. If assigning toxdid not rebindx, then nonsensical statements, such as6 = 5would be possible.The compile error is a static check that limits
return_internal_referenceto only work with classes or unions, as those will be mutable types within Python. I imagine that the ‘more complicated class template’ that works is returning a reference to a user-type.