[ctypes-users] accessing a C struct

Thomas Heller theller at python.net
Wed Feb 26 09:02:19 CET 2003

"Jim Vickroy" <Jim.Vickroy at noaa.gov> writes:

> Hello,
> I am just starting to use the ctypes module.
> A function in a dll, being accessed via ctypes, returns the address of a
> C
> structure.
> How can I use this address, from Python, to access fields in the
> structure?
> Do I define a ctypes Structure for the C structure?  If so, how do I set
> the return type of the C function to be this ctypes Structure?
> The reason I'm asking rather than trying it is that the C structure is
> quite complex (contains nested structures and unions) and so will
> require alot of time to specify as a ctypes Structure -- especially if
> that is the wrong approach.

This is the right approach.

You define the Structure as usual, then use POINTER() to create a
pointer class, and assign this to the function's restype value.

Here is a script which should get you started (the _ctypes.pyd extension
contains an exported function '_test_func_p_p' which accepts a pointer
and returns it unchanged, so this can easily be demonstrated):

from ctypes import CDLL, Structure, byref, POINTER, addressof

class POINT(Structure):
    _fields_ = [("x", "i"), ("y", "i")]


ctdll = CDLL("_ctypes.pyd")
func = ctdll._testfunc_p_p

r = POINT(1, 2)
print r

print addressof(r) # address of our point instance
print func(byref(r)) # passed through the function

# The functions returns an instance of the pointer class
func.restype = LPPOINT

result = func(byref(r))
print result.contents # and this is the 'contents' of the pointer

print result.contents.x, result.contents.y
r.x = r.y = 42
print result.contents.x, result.contents.y

When run, this script prints the following:

<__main__.POINT object at 0x009A6910>
<__main__.POINT object at 0x009ABB80>
1 2
42 42


More information about the Python-list mailing list