Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ensure that the same Python instance is always returned for a particular C++ instance?

I'm using Boost.Python to wrap a C++ library.

How do I ensure that the same Python instance (by object identity) is always returned for a particular C++ instance (by pointer identity)? I can't extend the C++ classes, but I can add a member variable (such as a PyObject * or a boost::python::handle<>) if that helps. I'm thinking that I should be able to cache the Python instance in the C++ instance, and return the cached instance instead of creating a new one. However, I can't figure out what wrapping code is required.

Example class to be wrapped:

class C {
public:
    boost::python::handle<> wrapper_;

private:
    C();
    C(const C &);
    ~C();
};

Can anyone offer advice?

like image 970
Mikael Lind Avatar asked Mar 04 '26 01:03

Mikael Lind


1 Answers

After investing some time into this very problem I came to the conclusion that it's more trouble than it's worth. I have resigned myself that id() will identify the (potentially short-lived) wrapper object and not the actual C++ object.

Instead I identify my C++ objects in some other way, e.g. by looking at the contents.

like image 88
drxzcl Avatar answered Mar 06 '26 14:03

drxzcl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!