开发者

boost::python string-convertible properties

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

class Bar {
...
    const Foo& getFoo() const;
 开发者_如何学Python   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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜