[C++-sig] (How) can I "attach" code/objects to a standard Pythonobject?

Hans Meine meine at informatik.uni-hamburg.de
Mon Aug 20 11:53:58 CEST 2007


Hi!

Am Montag, 20. August 2007 10:25:56 schrieb English, Mark:
> 1) I can't see
> a way to associate a given PyObject with a specific conversion mechanism or
> return policy in Boost without adding your own PyObject style type. Others
> may. Listen to them.
Yes, that sounds as if it might be impossible indeed.

> 2) Rather than going through the hoops mentioned below, you might be able
> simply to register a converter although lifetime management will presumably
> still be an issue.
Yes, I could register a converter (done that before), but I do not see how 
that would help here.

> In summary here's what I tried: Write a PyObject-style class implementing
> the PyBufferProcs, and then provide a converter for Boost to handle C++ ->
> Python, and a new return policy to handle lifetimes...

OK, I see that this solves my problem.  I even think that registering a 
converter from an arbitrary C++ class (which I would like to avoid 
introducing) to the standard PyBuffer type would help, too, as long as I can 
use the return policies.

For a brief moment, I thought it was worth trying return policies with my 
existing function, which looks like this:

PyObject * rawImageMemory(PythonImage const & image)
{
    return PyBuffer_FromReadWriteMemory(
        image.data(),
        image.width() * image.height() * image.bands() * sizeof(GrayValue));
}

[...]
class_<PythonImage>("PythonImage")
  .def("_rawBuffer", &rawImageMemory)
[...]

..but adding return_internal_reference<>() results in (not surprisingly):

.../boost/python/object/pointer_holder.hpp:176: 
error: 'boost::python::objects::pointer_holder<Pointer, 
Value>::pointer_holder(PyObject*) [with Pointer = _object*, Value = _object]' 
cannot be overloaded
.../boost/python/object/pointer_holder.hpp:111: error: 
with 'boost::python::objects::pointer_holder<Pointer, 
Value>::pointer_holder(Pointer) [with Pointer = _object*, Value = _object]'

I think my question arises from my poor understanding of how the 
return_value_policies actually work.  Yes, I do know that they provide some 
sort of hook mechanism which allows to execute code before and after the 
function call, but how is this related to the need to run code after the 
object returned by the object is destroyed?  It cannot be done with a 
destructor, since other functions may return objects of the same type with a 
different policy.  So I assume this has to do with the difference between the 
exported and the "held type" (which I have only a poor understanding of)?  
AFAICS, this should also be able to work with PyObject*s, no?

-- 
Ciao, /  /
     /--/
    /  / ANS



More information about the Cplusplus-sig mailing list