I'm exposing a C++ object meant to be subclassed in Python. When constructed these objects are referenced by some container C++ side. (actually std::map) One object can only be destructed after being explicitely removed from this container. However they are managed by Python and thus destroyed when there are no Python reference left to it but still remain referenced by the container.
I have to tell Python that when I constructed the object I kept a reference to it. I can't find any simple way to do that. I didn't find any calling policy that mean "increment the reference count to the returned object by one". Should I implement my own calling policy to do that ? (I have no idea how to implement a calling policy) Or is there another way to do it ?
I wrote a special policy which increases the reference count to the object being constructed.
template <class Base = default_call_policies>
struct incref_return_value_policy : Base
{
static PyObject *postcall(PyObject *args, PyObject *result)
{
PyObject *self = PyTuple_GET_ITEM(args, 0);
Py_INCREF(self);
return result;
}
};
It can then be used as any other policy :
class_<A>("A", init<>()[ incref_return_value_policy<>() ] );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With