Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::python string-convertible properties

I have a C++ class, which has the following methods:

class Bar {
...
    const Foo& getFoo() const;
    void setFoo(const Foo&);
};

where class Foo is convertible to std::string (it has an implicit constructor from std::string and an std::string cast operator).

I define a Boost.Python wrapper class, which, among other things, defines a property based on previous two functions:

class_<Bar>("Bar")
    ...
    .add_property(
        "foo",
        make_function(
            &Bar::getFoo,
            return_value_policy<return_by_value>()),
        &Bar::setFoo)
    ...

I also mark the class as convertible to/from std::string.

implicitly_convertible<std::string, Foo>();
implicitly_convertible<Foo, std::string>();

But at runtime I still get a conversion error trying to access this property:

TypeError: No to_python (by-value) converter found for C++ type: Foo

How to achieve the conversion without too much boilerplate of wrapper functions? (I already have all the conversion functions in class Foo, so duplication is undesirable.

like image 537
Alex B Avatar asked Nov 06 '22 14:11

Alex B


1 Answers

I ended up giving up and implementing something similar to custom string class conversion example in Boost.Python FAQ, which is a bit verbose, but works as advertised.

like image 68
Alex B Avatar answered Nov 11 '22 22:11

Alex B