[C++-sig] Instantiate a wrapped class in C++ and get the PyObject pointer

David Sveningsson ext at sidvind.com
Tue Apr 24 00:00:21 CEST 2007


>
> python's objects are all heap-allocated (and ref-counted). The above
> boost::python::object is only a tiny wrapper around a PyObject pointer,
> conveniently handling the ref counting for you.
> I'd think the construction itself thus already implies a copy construction
> to move the Fred instance into the heap.
> You are right that simply returning bar.ptr() like this is wrong, due to
> python potentially (or even likely) deleting the underlaying object, as
> soon
> as bar's destructor decreases the ref counter at the end-of-scope.
> Thus, you need to increment the counter before returning.

Ok, so I just increase the ref-count before returning and I'm all safe.

> However, the
> whole point of boost.python is to discourage you to use PyObject pointers
> directly (given how error-prone a business this is).

Yeah, but I need to fill a PyDict with keys and values. (And decrease the
ref-count after adding to the PyDict, as the dictionary should hold the
last reference)

I think I understand how this works now (the code seems to work too), thanks!




More information about the Cplusplus-sig mailing list