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

David Sveningsson ext at sidvind.com
Mon Apr 23 23:22:36 CEST 2007

> Can you rephrase the question, please ? The underlaying pointer is owned
> by
> the boost::python::object instance, no matter how often you access it via
> the ptr() member function. Thus, if you want to hand a reference to it to
> someone else, you have to make sure the reference counter is appropriately
> incremented (Read boost.python's reference guide for more on the topic.)

PyObject* foo(){
  boost::python::object bar = Fred(1,2,3);	// <-- Stack allocated
  return bar.ptr();

Since bar is allocated on the stack it will be destroyed once we return
from bar. Won't the pointer returned by ptr() only point to garbage after

PyObject* foo(){
  boost::python::object bar = new boost::python::object(Fred(1,2,3));
  return bar->ptr();

This time bar is allocated on the heap, so the pointer would still be
valid after returning from bar. But it will leak memory.

More information about the Cplusplus-sig mailing list