[C++-sig] union in C++ and BPL

David Abrahams david.abrahams at rcn.com
Tue May 28 16:38:17 CEST 2002


From: "chuzo okuda" <okuda1 at llnl.gov>


> I do not find any example of union, but does someone have any simple
> example of union?

There's no direct support for unions in Boost.Python.

> I have the following definition in our code:
>
> typedef union {
>    int ix;
>    double dx;
> } ListType;
>
> typedef struct {
>    bool isInt;
>    std::vector<ListType> list;
> } ItemList;
>
> and if isInt is yes, then would like to push int value to ItemList,
> otherwise to push double into ItemList.

Hmm. I think it would be better to consider the interface you'd like to see
from Python. You probably don't want to be creating ListType objects from
Python, do you? Wouldn't you rather just push python ints and floats onto
your vector?

> Here is my simple BPL code, but I am not entirely sure how to wrap union
> in python and pass the value to ItemList. (if you uncomment typedef int
> ListType and comment out union definition part, the code works nicely,
> though).
> I am aware that push(lst,10.1) is wrong, but then how to wrap 10.1 in
> ListType and pass as push(lst, ut)?

One way to handle this would be with the (undocumented) back_reference<T>
facility from boost/python/back_reference.hpp. You can wrap a function
which takes back_reference<int> (or back_reference<double>) as a parameter;
that will give you a reference to the source python object in addition to
the converted value.

void ItemList_push(ItemList& l, back_reference<double> x)
{
    ListType element;

    if (PyInt_Check(x.reference())) // was the source object an Int?
    {
        element.ix = PyInt_AsLong(x.reference().get());
    }
    else
    {
        element.dx = x.get();
    }
}

*** Pearu, I think this might be a way to work around some of your issues
as well ***

-Dave







More information about the Cplusplus-sig mailing list