[C++-sig] boost::python::object referencing c++ object

Bjorn Pettersen BPettersen at NAREX.com
Sat Jan 4 00:22:13 CET 2003


> From: David Abrahams [mailto:dave at boost-consulting.com] 
> 
> "Bjorn Pettersen" <BPettersen at NAREX.com> writes:
> 
> >   template <class T>
> >   void set(const std::string& name, const T& value) {
> >     PyObject* key = PyString_FromString(name.c_str());
> >     object val(value);
> >     PyDict_SetItem(interpreter()->mainmodule(), key, val.ptr());
> >     Py_DECREF(key);
> >   }
> 
> Why make life hard for yourself?
> 
>   template <class T>
>   void set(const std::string& name, const T& value) {
>     interpreter()->mainmodule()[name] = value;
>   }
> 
> Of course, this relies on interpeter()->mainmodule() 
> returning an object (or dict, or...)

Thanks (this code was written before we moved to BPL :-)

[...]
> Perhaps you'd like the resulting Python object to contain a 
> raw pointer to the argument?  In that case, the caveat is 
> that if the lifetime of the C++ object ends before that of 
> the Python object, that pointer will dangle and using the 
> Python object may cause a crash.
[example..]

Understood. Thanks for the code.

-- bjorn




More information about the Cplusplus-sig mailing list