extracting null pointer address from PyCObject with ctypes

Aaron "Castironpi" Brady castironpi at gmail.com
Sat Oct 11 04:43:20 CEST 2008

On Oct 10, 7:59 pm, Gordon Allott <gordall... at gmail.com> wrote:
> Aaron "Castironpi" Brady wrote:
> > Yes, well said.  But no, not true, not necessarily.  You can choose/
> > change return types with your code.  If the call is defined already
> > and you can't change the return, just define a new one that returns
> > long.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
> the problem is that the pointer or long or whatever it is thats returned
> won't be the data I am after. the code for PyCObject_FromVoidPtr is as
> follows:
> PyObject *
> PyCObject_FromVoidPtr(void *cobj, void (*destr)(void *))
> {
>     PyCObject *self;
>     self = PyObject_NEW(PyCObject, &PyCObject_Type);
>     if (self == NULL)
>         return NULL;
>     self->cobject=cobj;
>     self->destructor=destr;
>     self->desc=NULL;
>     return (PyObject *)self;
> }
> it obviously creates a new PyObject and returns that, which has already
> happened once (the address I am after is passed to python via
> PyCObject_FromVoidPtr(adress_i_am_after, NULL), doing that puts the
> address I am after into the .cobject attribute of a new pyobject
> structure and passes that to the python script via the 'display' key in
> a dictionary.
> If I were to then take the pycobject in this display key and pass it via
> ctypes into PyCObject_FromVoidPtr it would simply create a new pycobject
>  and put a pointer to the old pycobject in the new pycobject's .cobject
> attribute. it just means that I am getting further and further away from
> where I want to be surely? if I were to take the current pointer at this
> stage, to get to the address I actually want in C it would have to
> follow something along the lines of
> long address_i_want = (long)(new_pycobj->cobject->cobject);
> What would be great is if there is some easy simple way of accessing the
> .cobject attribute of the first pycobject thats passed via the
> dictionary to python.
> --
> Gord Allott (gordall... at gmail.com)
>  signature.asc
> < 1KViewDownload

You are hard to follow.  There is the 'cast' function, which I've had
some success with, even in adding pointers and offsets.  It took a
look at the code for it though, and calling an undocumented version of
it.  I can post that later if you don't have luck the same.  You can
write extension modules to do that as well, and there's always a
Google search which personally I forget half the time too.  Last, you
haven't mentioned an attempt with PyCObject_AsVoidPtr yet:

void* PyCObject_AsVoidPtr(PyObject* self)
    Return the object void * that the PyCObject self was created with.

Where does that get you?

More information about the Python-list mailing list