[C++-sig] return reference to same python object

Andreas Beyer beyer at fli-leibniz.de
Wed Jan 4 16:28:54 CET 2006


Jonge, W. de (Cebra) wrote:

>Hi Andreas,
>
>Thanks for the reply, as my objects are created in C++ space I think the
>latter thread applies
>(http://mail.python.org/pipermail/c++-sig/2005-April/008805.html). 
>Did you ever got something working, and if so how? 
>
If you exactly follow David's suggestions it works. The example that I 
gave works with David's solution.

>With or without using
>the to_python_converter, this sounds as a good solution to me and I
>would also think to use a global map mapping C++ pointers to already
>existing python wrappers.
>  
>
I recommend *not* to create a map for C++ pointers. You are doubbling 
information that BP already has. You also don't gain a lot. In order to 
use the map, you will have to check if a certain smart pointer is 
already registered in the map before you return it to python. (You will 
do this in some kind of thin-wrapper function.) At the same point in 
your code you could also just call hold_python() - it does the job for you.
The problem here: you have to create a wrapper for all functions 
returning the smart pointers.

I never created a to_python_converter (don't know how to do that). 
However, you may not need it anyway.
My workaround is: call hold_python() immediately after creating an 
object. Afterwards BP 'knows' the respective smart pointer. There is no 
need to call hold_python() at any other location in your code.
The drawback: I couldn't find a way (in my code) that is not intrusive 
into the originial C++ code. What I am doing now is something like this:

A_ptr my_factory_method()
{  // this is my original factory method, which I had to modify
    A_ptr * a = create_new_A();
#ifdef BP_WRAPPING
    hold_python(a); // register new smart pointer at boost.python
#endif
    return a;
}


Of course you have to define BP_WRAPPING and hold_python() somewhere.
I am sure there are better solutions. Yet, I don't know them.

Andreas




More information about the Cplusplus-sig mailing list