[C++-sig] Re: Automatic (implicit ?) type conversion for a data member of a struct.

David Abrahams dave at boost-consulting.com
Mon May 26 22:15:43 CEST 2003


"pj" <pjdurai at hotmail.com> writes:

> Greetings.
>
> Generally how would I enable automatic conversion for a given C++ type ?
>
> To be specific.
>
> I know how to expose this class to Python and exposing a function returning
> this struct.
> Its pretty easy due to the power of boost-python.
>
> class MyStruct
> {
>     std::string name;
> }
>
> MyStruct fuc1();
>
>
> What I cant figure out is how would I do this if the 'name' is not a type
> understood by boost-python.
> say ..
>
> class MyString;
>
> class MyStruct
> {
>     MyString name;
> }
>
> MyStruct fuc1();
>
> I _dont_ want to wrap the whole 'MyString' class to Python.
>
> I would like to expose 'MyStruct' to python so that the 'name' data
> member of MyStruct is _automatically_ _exposed_ as a python string ?
>
> I have tried the basic documentation and couldnt find the
> information I need.
>
> Appreciate your time.

See my response to Gavin Doughtie about rvalue converters.  There's
one detail you have to keep in mind, though: normally class data
members are exposed as lvalues when you do,
e.g. def_readonly(&MyStruct::name), so that you can do something like:

     >>> x = MyStruct()
     >>> x.name.mutate() # modify x.name
     >>> x.name.value()

and see the expected result.  Of course MyString objects are special
and can only be converted Python strings which copy their data.  If
you just wrap "name" in the usual way you'll get runtime errors when
you try to access it as an lvalue because there are no registered
lvalue converters.  Instead you need to make a property and use call
policies, e.g.:

        .add_property(
            "name"
           , make_getter(
                &MyStruct::name
              , return_value_policy<return_by_value>())
           , make_setter(&MyStruct::name))

        ...

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list