[C++-sig] Boost.Python C++ object reference in Python: unexpected behaviour.

Christoff Kok christoff.kok at ex-mente.co.za
Tue Jun 2 16:36:31 CEST 2015


Hi Stefan,

Thank you very much. That makes sense and my tests prove it. The code runs
as expected when I reserve enough space for the vector.

I do not quite get it why it works in C++ and not python. I know too little
about the C++ and python run-time.
I guess that the C++ run-time automatically updates objects holding
references to its new address, whereas this is not the case in the Python
run-time.
Fixing that issue for me is way over my head at the moment.

Thank you very much for spending the time to think about the problem and
kudos to you for discovering the reason.


I'm not sure how to solve the problem either, my objects are uniquely
identifiable.
I might be able to override the python objects' __getattribute__ methods
and set the python object to that of its parent container's instance (only
if the vector has not been resized).
I don't know if this will work, This might slow the code down a bit as
well. I'll try it none the less.

Thanks again Stefan.

Regards,
Christoff

On 2 June 2015 at 15:11, Stefan Seefeld <stefan at seefeld.name> wrote:

> Christoff,
>
> I just noticed I wasn't really answering the real problem you report,
> which is the crash.
>
> I believe the problem is in your code: You create two vectors of
> value-types (cars and factories). Then you take references to the stored
> objects, while there is no guarantee that the objects' addresses won't
> change over time. In particular, there is a good chance of these objects
> to be copied as the vector gets resized as new objects are added beyond
> their current capacity.
>
> As a test, I called
>
> vector<...>::reserve(32)
>
> on each of the vectors right in the Factory and Manufacturer
> constructors, with the effect of allocating enough storage upfront so
> that in your sample code no re-allocation is required, and thus objects
> won't be copied around. This prevents the crash from happening for me.
>
> Obviously this is just to illustrate the problem; it's definitely not a
> solution to your problem, which still is that you reference objects
> beyond their lifetime.
>
> HTH,
>         Stefan
>
> --
>
>       ...ich hab' noch einen Koffer in Berlin...
>
> _______________________________________________
> Cplusplus-sig mailing list
> Cplusplus-sig at python.org
> https://mail.python.org/mailman/listinfo/cplusplus-sig
>



-- 
Christoff Kok
Software Engineer
Ex Mente

http://www.ex-mente.co.za
christoff.kok at ex-mente.co.za
PO Box 10214
Centurion
0046
South Africa
tel: +27 12 743 6993
tel: +27 12 654 8198
fax: +27 85 150 1341
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20150602/4348fc6f/attachment.html>


More information about the Cplusplus-sig mailing list