Fw: [C++-sig] Pyste and STL types

Nicodemus nicodemus at globalite.com.br
Tue Mar 18 18:41:30 CET 2003


David Abrahams writes:

>Patrick Hartling <patrick at vrac.iastate.edu> writes:
>  
>
>>In that case, it would make sense if Pyste ran into a problem with a
>>class containing a public data member that is a union type.  I would
>>grant that the C++ class I have in mind should probably encapsulate
>>its data better, but in the meantime, should exclude() work to keep
>>the union data member out of the mix?  
>>    
>>
>Probably a good idea.  
>

That's the way it should be, but there's a bug in the implementation. I 
will fix it as soon as possible.

>Eventually, this is the sort of problem that
>can be handled by something like Pyste but not easily by Boost.Python
>alone.  In order to do the wrapping, you'd need to provide Pyste with
>a function that it could use to determine which member of the union
>was "active".
>
>Come to think of it, I guess you could use Boost.Python properties
>with appropriate C++ accessor functions to expose a union data member.
>

I don't know much about Unions, so please correct me if any statement 
below is wrong.

 From what I understand, unions act exactly like a struct, except that 
it's members all share the same adress space. The only point to this is 
to save memory. The union doesn't keep track of each variable is 
"active", the programmer must take care of that:

union Test
{
    float d;
    int i;
};

void main()
{
    Test t;
    t.d = 3.0;
    cout << t.i << endl;
}

Using t.i in the example above gives you garbage. The programmer should 
only access t.d, or set a new value for the union using t.i. Given that, 
I believe that Boost.Python could expose it exactly like an struct:

    class_<Test>("Test")
        .def_readwrite("d", &Test::d)
        .def_readwrite("i", &Test::i)
    ;

This currently fails, apparently because of an internal mechanism of 
Boost.Python involving polimorphism. From what I gather from the error 
message, Boost.Python tries to derive from Test to check for polimorphic 
behaviour, and unions can't be subclassed. So, a possible solution would 
be to specialize a class_ to take in account the details of a union 
(lack of polimorphism, no derivation):

    union_<Test>("Test")
        .def_readwrite("d", &Test::d)
        .def_readwrite("i", &Test::i)      
    ;

What you think?






More information about the Cplusplus-sig mailing list