[C++-sig] converting objects to python..

David Abrahams dave at boost-consulting.com
Wed Apr 30 02:21:50 CEST 2003


Dominique Devriese <dominique.devriese at student.kuleuven.ac.be> writes:

> Hi, 
>
> I have been looking at this for some time, and I can't seem to find
> it.  Maybe someone here can help ?  
>
> (I'm using Boost.python to export the api of an app that i want to
> embed python in.. ( http://edu.kde.org/kig in case someone is
> interested ) )
>
> I'm trying to call a python function from C++ code with some
> arguments.  The arguments are of type "const ObjectImp*", where
> ObjectImp is the abstract base class of a whole lot of other types.
> All of them are properly wrapped, and I have tested the wrapping in
> different situations, and it works.  The problem is that I can't seem
> to find how to convert a "const ObjectImp*" to a PyObject.  I tried:
>
> const ObjectImp* the_object_imp_pointer;
> object o( the_object_imp_pointer );
> use( o.ptr() );
> object o2( *the_object_imp_pointer );
> use( o2.ptr() );
>
> ( and a whole lot of other things that would only make me look stupid
> here, so i'll omit those ;) )
>
> In both cases, the object constructor throws an error_already_set
> exception

What's the Python exception behind it?

> and from the debugging in boost.python internals I've done, it
> appears that this happens because the lib doesn't have a converter
> registered for the types.
>
> I thought about trying to write a converter myself, but then I thought
> that this would be stupid, since I wouldn't know how to do this,
> unless i found out how boost.python PyObject's work, and it seemed
> more intelligent to just ask here first ;)
>
> At one point, I also thought that the problem would be that i should
> first downcast the pointers to their "real" type, and try to convert
> that, but then I thought that would not be the case, since you're
> using typeid() in the conversion stuff, and that only takes into
> account the "real" type, not the formal type, so downcasting is not
> necessary..
>
> Anyway, I'm kinda stuck on this..  Could you give me some pointers on
> where to look ?

http://www.boost.org/libs/python/doc/v2/ptr.html

Consider:

   object o( ptr(the_object_imp_pointer) );

Equivalent to:

   object o( ref(*the_object_imp_pointer) );

But beware dangling reference in Python.

   object o( *the_object_imp_pointer );

is safer, but incurs a copy (and slicing) of your base class.

Using boost::shared_ptr instead of raw pointers works best of all if
it's an option.

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





More information about the Cplusplus-sig mailing list