ctypes pointer to structure memory swap

Nobody nobody at nowhere.com
Fri Mar 18 18:42:02 EDT 2011


On Fri, 18 Mar 2011 15:16:40 -0700, Wanderer wrote:

> Thanks for the reply, but I'm still not sure I understand. Why should
> Object1 be at address1 and Object2 be at address2 and the next moment
> Object2 is at address1 and Object1 is at address2? I'll try casting
> them to see what the value is before and after calling
> ReleaseCameraSettingStruct.

QCamSettingsEx is a ctypes Struct object. The pSettingsID "field" is a
ctypes field, not a Python field. It will contain a "bare" pointer to the
C-struct for the QCamSettingId object.

The point of a ctypes Struct is to store data in a format usable by C
code, i.e. the memory layout will match that of a C struct. In particular,
pointers within that struct will be pointers to C-compatible data (e.g. C
structs), not pointers to Python objects. If you access the fields from
Python, ctypes will generate Python objects on-the-fly from the raw data.

Whenever you read the pSettingsID field, ctypes will generate a ctypes
pointer object (LP_QCamSettingId?) which wraps the underlying C pointer.
If you dereference that, ctypes will generate a Python QCamSettingId
object which wraps the C struct.

As you aren't storing the references, as soon as the print statement
completes, the reference count will drop to zero and the object will be
deallocated. The next time you reference pSettingsID or pSettingsID[0], a
new object will be constructed. The addresses (and thus IDs) of the Python
objects are entirely arbitrary.




More information about the Python-list mailing list