To access the elements of a union in ctypes, define a class that inherits from ctypes.Union, list its members in _fields_, create an instance, and read or write the members with normal attribute access such as data.integer. All members share the same memory, so you can only rely on the member you wrote last. Reading any other member reinterprets the same bytes as a different type.
This guide shows how to define a union, read and write each member, inspect the raw bytes, and keep track of which member is valid. The examples run on Python 3.12 or newer on a standard 64-bit platform.
A C union stores all of its members at offset 0. Its size is the size of its largest member, plus any padding the alignment requires. In ctypes, ctypes.Union gives you the same layout, which is why it is used to mirror C union declarations when you call a shared library or parse a binary format.
The union is 20 bytes because the c_char * 20 member is the largest. Every member starts at offset 0, so writing to one member overwrites the bytes the others read.
Create an instance by calling the class. All bytes start as zero. You can also pass one member as a keyword argument.
Use keyword arguments when you know which member you are initialising. Passing several members at once is legal, but only the last one assigned is meaningful, so avoid it.
Reading a member you did not write reinterprets the stored bytes. The result is not an error, and it is not a conversion: the bits are the same, but they are interpreted with another type.
Two things to note. First, 3.14 does not come back as 3.14: a c_float holds a 32-bit IEEE 754 value, so the printed Python float shows the nearest representable number. Second, the integer 1078523331 is simply the bit pattern of that float. This reinterpretation is the technique people use on purpose when they want to look at the bits of a float.
The exact integer is what a little-endian machine with a 4-byte c_int and c_float prints. The value depends on the platform's byte order and on the size of c_int, so do not hard-code such numbers in portable code.
A c_char array member behaves as bytes. Assign a bytes object that fits in the array, and read it back as bytes. Reading stops at the first NUL byte.
data.integer is the first four bytes of b"hello" read as a little-endian integer. If you assign a bytes value longer than the array, ctypes raises ValueError. Use .decode("utf-8") only on bytes you know are valid text. After you store a float or an integer, decoding the string member can raise UnicodeDecodeError, because the raw bytes are not text.
When you need to see exactly what the union holds, convert it to bytes, or use from_buffer_copy to build a union from existing bytes.
A union does not remember which member is active. C code solves this with a separate tag field inside a structure. You can do the same in ctypes by wrapping the union in a Structure with a kind field, and checking kind before you read.
Declaring payload in _anonymous_ lets you write v.i instead of v.payload.i.
| Mistake | What happens | Fix |
|---|---|---|
| Reading a member that was not written last | You get reinterpreted bits, not a converted value | Store a tag next to the union and check it |
Assigning str to a c_char array | TypeError, because the member expects bytes | Use b"text" or "text".encode() |
Assuming 4-byte int and fixed byte order | Different numbers on other platforms | Use fixed-width types such as c_int32, and set endianness explicitly if the layout matters |
| Decoding a non-text member as UTF-8 | UnicodeDecodeError | Decode only when you wrote text |
You can read them, but they show the same bytes interpreted as two types. Only the member you wrote last carries meaningful data unless you intentionally want the reinterpretation.
A Structure lays its fields out one after another, so each holds its own value. A Union places every field at offset 0, so they overlap and the size equals the largest member.
Call ctypes.sizeof(Data) on the class or an instance. It returns the size of the largest member plus alignment padding.
No. Neither C nor ctypes records the active member, so keep a separate tag field if the meaning of the data changes at run time.
Define a union by subclassing ctypes.Union and listing members in _fields_. Access members with attribute syntax, remember that they all share offset 0, and treat only the last written member as valid. Use bytes(data) to inspect the raw memory, and a tagged structure with an anonymous union when you need to know which member is active.