Storing a C pointer in a Python class instance

sturlamolden sturlamolden at
Tue Sep 29 18:42:38 CEST 2009

On 29 Sep, 10:27, "lallous" <lall... at> wrote:
> Hello
> From my C extension module I want to store a C pointer in a given PyObject.
> The only way I figure how to do it is to use Py_BuildValues and store the
> poiner casted to Py_ssize_t,

Formally, you should cast the pointer to Py_intptr_t, as it has the
same size as void*. Py_ssize_t has the same size as size_t, but the C
standard does not mandate that sizeof(void*) == sizeof(size_t). In
fact there are segment and offset architectures where this is not
true. Casting a pointer to Py_ssize_t accidentally works if you have a
flat address space.

> Can it be done differently?

You can use PyCObject, or write your own extension type that wraps the
pointer (very easy to to with Cython or Pyrex). The advantage of using
an extension type is you have a guarantee from Python on the
deallocator method being called (cdef __dealloc__ in Cython). If the
pointer references a resource that needs to be closed, this is safer
than using a __del__ method in a Python class.

More information about the Python-list mailing list