Boost + Python C/API: Mixing python return types with boost return types

Mike Rovner mike at nospam.com
Thu Oct 9 12:32:07 EDT 2003


Steve Knight wrote:

It's better ask boost.python related questions in comp.lang.python.c++
group/list.

> I'm new to Boost & Python and I'm diving straight in by trying to
> write an extension module to a third party library.  Foolishness
> probably, but I don't have much choice!

Why, it's usually fun and rewarding.

> My question is how can I write a C++ method that will either return a
> boost wrapped C++ class or a Python object type depending on some
> internal value?

In either case you return a python object, that is what matters.

> So I want to do something like:
>
> PyObject* Variant::getValue() {

python::object Variant::getValue() {

>
>      switch (type) {
>          case INT:
>              return Py_BuildValue("i", union.int);

                 return python::object(union.int);

>              break;
>          case SOMECLASS:

                 return python::object(*union.p_someclass);

>              ??????
>      }
> }
>
> But I can't work out how to get my switch to construct and return my
> boost C++ wrapped object in this scheme.  I'm getting round it by:
>
> SomeClass Variant::getSomeClass() {
>      SomeClass s(*reinterpret_cast<SomeClass*>(union.p_void));
>      return s;
> }
>
> But it seems a bit nasty.  Any ideas?

In case you keep void pointer in union you'll need that nastiness anyway.
Why can't you keep a pointer to someclass in the union instead?

BTW, more complete example of the code (better working one) will definitely
clarify communications.

HTH,
Mike








More information about the Python-list mailing list