[C++-sig] Lifetime of Python object for a pointer argument
Min Xu
minxu at sci.ccny.cuny.edu
Sat Feb 16 16:57:01 CET 2002
Hi,
I am a newbie of boost python. In the process of converting a SWIG
wrapping of a C++ library to boost python, I encounter the following
problem:
// C++ part
class grid
{
public:
grid() { ... }
...
};
class geometry
{
public:
geometry(const grid * gd) : gd(gd) {}
const grid* getGrid() const { return gd; }
private:
const grid* gd;
};
// Wrapper
#include <boost/python/class_builder.hpp>
namespace python = boost::python;
PyObject* to_python(const grid* g) {
return to_python(*g); // convert const grid* in terms of const
grid&
}
BOOST_PYTHON_MODULE_INIT(ngf2)
{
try
{
python::module_builder this_module("ngf2");
python::class_builder<grid> grid_class(this_module, "grid");
grid_class.def(python::constructor<>());
python::class_builder<geometry> geometry_class(this_module,
"geometry");
geometry_class.def(python::constructor<const grid*>());
}
...
}
The compilation works well (the newest CVS version of boost python).
In python:
>>> from ngf2 import *
>>> a=geometry (grid())
>>> a.getGrid ().a()
8.6723632812500586 # corrupted as grid() is deleted automatically?
>>> g=grid()
>>> b=geometry (g)
>>> b.getGrid ().a()
1.0 # expected.
>>> del g
>>> b.getGrid ().a()
1.3285421879284814e-269 # corrupted
I understand it may be a ref counting problem. Is there any way to make
the first idiom work?
Thanks!
Min Xu
More information about the Cplusplus-sig
mailing list