CodeBlanks Logo Icon CodeBlanks

Structure

Learn C structs with ctypes.Structure.

What is a Structure?

ctypes.Structure represents C structs in Python. You specify field names and types with the _fields_ list.

For example class Point(Structure): _fields_ = [('x', c_int), ('y', c_int)] creates a struct with x and y fields. You instantiate with p = Point(3, 4) and access with p.x. This lets you use C library structs directly in Python, which is very useful for reading binary data.

Field access

After creating a Structure instance you access fields with a dot: p.x, p.y. Both reading and writing work.

The field order matches the _fields_ list. Point(3, 4) sets the first field to 3 and the second to 4. Nested structures are supported: a field's type can be another Structure. This lets you easily model complex C data structures in Python.

Practice Define a point with Structure

Import the module with import ctypes. Write a Point(ctypes.Structure) class; define _fields_ = [('x', ctypes.c_int), ('y', ctypes.c_int)]. Create an instance with Point(3, 4) and print p.x and p.y.

Starter code

main.py
# write the Point struct
# create an instance and print

Sample solution

main.py
import ctypes

class Point(ctypes.Structure):
    _fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int)]

p = Point(3, 4)
print(p.x, p.y)

Expected output

3 4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which attribute does Structure use?

main.py
class Point(ctypes.Structure):
    _fields_ = [('x', c_int)]
  • __init__
  • __dict__
  • __slots__
  • _fields_ Correct answer

Explanation: answer: _fields_. This list defines field names and types.

2 Match Structure concepts

Term Meaning
Structure C struct base
_fields_ Field list
Point(3,4) Creating an instance
p.x Field access

3 Complete the Structure definition

Question
class Point(ctypes.____):
    _fields_ = [('x', c_int)]
Answer
class Point(ctypes.Structure):
    _fields_ = [('x', c_int)]

Explanation: A struct derives from ctypes.Structure.

All lessons in Expert