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

chuzo okuda okuda1 at llnl.gov
Fri May 24 21:06:16 CEST 2002


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

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.

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)?

------------ code -------------
#include <boost/python/module.hpp>
#include <boost/python/class.hpp>

using namespace boost::python;
#include <iostream>
using std::cout;
using std::endl;
#include <vector>

//typedef int ListType;
union listType {
   int ix;
   double dx;
};
typedef union listType ListType;

struct itemList {
   bool isInt;
   std::vector<ListType> list;
};
typedef struct itemList ItemList;

void push(ItemList& l, ListType a) {
   l.list.push_back(a);
}

void show(ItemList l) {
   for (int i=0; i<l.list.size();i++) {
      if (l.isInt)
         cout << l.list[i].ix << ' ';
      else
         cout << l.list[i].dx << ' ';
   }
   cout << endl;
}

BOOST_PYTHON_MODULE_INIT(unionTest)
{
   using namespace boost::python;
   module ("unionTest")
      //.def_readwrite("ix", &listType.ix)
      //.def_readwrite("dx", &listType.dx)

      .def("push",push)
      .def("show",show)
      .add(
           class_<itemList>("itemList")
           .def_init()
           .def_readwrite("isInt", &itemList::isInt)
           )
      ;
}
-----------------------------------------------

gps02(223) python
Adding parser accelerators ...
Done.
Python 2.2 (#1, Jan 22 2002, 14:39:03) [C] on osf1V5
Type "help", "copyright", "credits" or "license" for more information.
>>> from unionTest import *
>>> lst=itemList()
>>> lst.isInt = 0
>>> push(lst,10.1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: bad argument type for built-in operation

Thank you very much
Chuzo





More information about the Cplusplus-sig mailing list