Question

I have a C++ function Obj *new_object(const char *name). It returns a new object, allocated from a private pool. That object should be freed by free_object(Obj *obj) (and not by free() or delete). How can I arrange my boost.python wrappers so that when the python obj goes out of scope (and gc is called) free_obj will be called?

Était-ce utile?

La solution

I think the most convenient way to do this would be to make sure your Boost.Python class declaration wraps both Obj and boost::shared_ptr<Obj>.

Then, use boost::python::make_constructor to instantiate the object upon construction. Your returned boost::shared_ptr<Obj> should set its own destructor (in your case, free_object()). Here is a sketch of this solution:

static boost::shared_ptr<Obj> init_from_c_string(const char* name) {
  //set destructor upon shared pointer initialisation
  return boost::shared_ptr<Obj>(new_object(name), &free_object);
}

//at your module scope, declare "Obj" like this
using namespace boost::python;
class_<Obj, boost::shared_ptr<Obj>>("Obj", "Obj docstring", no_init)
    .def("__init__", make_constructor(&init_from_c_string, default_call_policies(), (arg("name"))), "Constructs a new object with a given name.")
    //other .def and similar
;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top