I am using Python ctypes to interface with some C code.

For a particular C function I am trying to call, I need to pass a pointer to a field in a structure. The field is not the first field. It looks like the byref() function will do this, so I am trying to use;

 byref(obj,myObject.data.offset)

where myObject is defined thus:

class myObject(Structure):
    _fields_ = [
        ('meta1',c_void_p),
        ('meta2',c_int),
        ('meta3',c_int),
        ('data',c_char * 10)
    ]

However, this call is failing because the system that it needs to run on is only running Python version 2.5, and the ability to add the optional offset parameter was added in 2.6.

I have tried byref(obj.data) but this results in the error: TypeError: byref() argument must be a ctypes instance, not '_ctypes.CField'.

How can I achieve the needed result in versions < 2.6 (it is not practical to always require 2.6 as this needs to work in systems where upgrading is not always possible).

有帮助吗?

解决方案

In 2.5, ctypes has addressof, so you can use the following:

obj = myObject()
arg = c_char_p(addressof(obj) + myObject.data.offset)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top