[C++-sig] How to create instance using existing C++ object

David Abrahams dave at boost-consulting.com
Wed Feb 1 22:40:50 CET 2006


Vladimir Ofitserov <vladimir at inktomi.com> writes:

> Let say I have a C++ function that gets instance of noncopyable object 
> (CDoc for example) and I want to implement this function in python 
> module, wrapping CDoc class using Boost.Python:
>
> void MyFunction( CDoc *pDoc ) {
>
>     // want a wrapper that is just a pointer/reference/shared_ptr
>     class_<CDoc, CDoc&, noncopyable> cdoc( "CDoc", noinit );
                       ^
                       !! What is that supposed to be?  
                       The library definitely does not expect a
                       reference type here!

>     cdoc.def(...);
>     cdoc.def(...);
>
>     // now how do I create instance of "cdoc" around pDoc
>     // using cdoc::operator()?
>     object odoc = cdoc( *pDoc );
>
>     // calling python module with new object instance
>     call_method<void>( pymodule, "myfunction", odoc );
> }

You've left out a *lot* of information!  E.g., what is
cdoc::operator()?  But anyway...

> The main problem is that I could not find any documentation on how to 
> create python wrapper around existing object. Only thing I've seen is 
> Python Wiki FAQ article that has correct problem statement but 
> *incorrect* answer:
>
> http://wiki.python.org/moin/boost.python/FAQ


You might try this:

    namespace python = boost::python;

    python::object identity(python::object o) { return o; }
    python::object py_id(identity);
    python::object py_cdoc_instance
       = py_id(boost::ref(some_cpp_cdoc_instance));

    // Warning: if some_cpp_cdoc_instance is destroyed before
    // py_cdoc_instance, crashses may ensue!

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




More information about the Cplusplus-sig mailing list