Sub topic 5
Describing structs and arrays with memory layouts
This chapter assumes you know MemorySegment, Arena and ValueLayout from the earlier chapters. You should also know how C lays out structs and arrays: field order, alignment and padding.
Why layouts matter
A MemorySegment is only bytes. Reading a C struct through raw offsets means you hard-code numbers such as 4 and 8. Those numbers break when someone adds a field or the platform changes.
A memory layout is a Java object that describes the shape of a block of memory. It records sizes, alignment, field names and nesting. Your code can then ask the layout for offsets instead of guessing them.
You have already used ValueLayout for single values. This chapter covers the composite layouts:
| Layout | Created with | C equivalent |
|---|---|---|
| Struct | `MemoryLayout.structLayout(...)` | `struct { ... }` |
| Union | `MemoryLayout.unionLayout(...)` | `union { ... }` |
| Sequence | `MemoryLayout.sequenceLayout(n, element)` | `T name[n]` |
| Padding | `MemoryLayout.paddingLayout(bytes)` | Compiler-inserted gap |
Struct layouts
A StructLayout places its members one after another in the order you list them. It does not insert padding for you. This is the most common surprise for C programmers.
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
public class MisalignedDemo {
public static void main(String[] args) {
try {
// C would pad this struct. Java refuses to guess.
StructLayout bad = MemoryLayout.structLayout(
ValueLayout.JAVA_BYTE.withName("tag"),
ValueLayout.JAVA_INT.withName("count"));
System.out.println(bad);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: the int would start at offset 1");
}
}
}The int would start at byte 1, but JAVA_INT requires 4-byte alignment. structLayout checks every member and throws IllegalArgumentException. You must write the padding yourself.
Here is the C struct:
// struct record { char tag; int count; double value; };On a typical 64-bit platform, the compiler puts tag at offset 0 and count at offset 4. It puts value at offset 8, so the total size is 16. In Java you describe the three bytes of padding explicitly:
import java.lang.foreign.Arena;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemoryLayout.PathElement;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
public class RecordDemo {
static final StructLayout RECORD = MemoryLayout.structLayout(
ValueLayout.JAVA_BYTE.withName("tag"),
MemoryLayout.paddingLayout(3),
ValueLayout.JAVA_INT.withName("count"),
ValueLayout.JAVA_DOUBLE.withName("value")).withName("record");
static final long TAG = RECORD.byteOffset(PathElement.groupElement("tag"));
static final long COUNT = RECORD.byteOffset(PathElement.groupElement("count"));
static final long VALUE = RECORD.byteOffset(PathElement.groupElement("value"));
public static void main(String[] args) {
System.out.println("size = " + RECORD.byteSize()); // 16
System.out.println("alignment = " + RECORD.byteAlignment()); // 8
System.out.println(TAG + " " + COUNT + " " + VALUE); // 0 4 8
try (Arena arena = Arena.ofConfined()) {
MemorySegment rec = arena.allocate(RECORD);
rec.set(ValueLayout.JAVA_BYTE, TAG, (byte) 'A');
rec.set(ValueLayout.JAVA_INT, COUNT, 7);
rec.set(ValueLayout.JAVA_DOUBLE, VALUE, 2.5);
System.out.println((char) rec.get(ValueLayout.JAVA_BYTE, TAG)
+ " " + rec.get(ValueLayout.JAVA_INT, COUNT)
+ " " + rec.get(ValueLayout.JAVA_DOUBLE, VALUE));
}
}
}Note three things in this code:
paddingLayout(3)takes a size in bytes in JDK 22 and later. Earlier preview versions took bits.- The alignment of a struct is the largest alignment of its members. Here it is 8, because of the
double. arena.allocate(RECORD)allocatesRECORD.byteSize()bytes aligned toRECORD.byteAlignment(). That is why the latersetcalls pass the alignment checks.
Names and paths
withName labels a member. A path is a sequence of PathElement values that navigates from the outer layout to a nested member. byteOffset(path...) returns the distance in bytes from the start of the outer layout to that member.
Paths are what make nesting practical. Suppose a line is made of two points. The inner x of the end point is found by name:
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemoryLayout.PathElement;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
public class NestedDemo {
static final StructLayout POINT = MemoryLayout.structLayout(
ValueLayout.JAVA_INT.withName("x"),
ValueLayout.JAVA_INT.withName("y"));
static final StructLayout LINE = MemoryLayout.structLayout(
POINT.withName("start"),
POINT.withName("end"));
public static void main(String[] args) {
long endY = LINE.byteOffset(
PathElement.groupElement("end"),
PathElement.groupElement("y"));
System.out.println(endY); // 12
System.out.println(LINE.byteSize()); // 16
}
}groupElement selects a member of a struct or union, either by name or by position. If a name does not exist, the call throws IllegalArgumentException. This makes a renamed field fail at class initialization instead of corrupting data.
Sequence layouts
A SequenceLayout repeats one element layout a fixed number of times. It models a C array of known length. You can build an array of structs and address any field of any element with one path:
import java.lang.foreign.Arena;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemoryLayout.PathElement;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SequenceLayout;
import java.lang.foreign.StructLayout;
import java.lang.foreign.ValueLayout;
public class ArrayOfPoints {
static final StructLayout POINT = MemoryLayout.structLayout(
ValueLayout.JAVA_INT.withName("x"),
ValueLayout.JAVA_INT.withName("y"));
static final SequenceLayout POINTS = MemoryLayout.sequenceLayout(3, POINT);
static long offset(long index, String field) {
return POINTS.byteOffset(
PathElement.sequenceElement(index),
PathElement.groupElement(field));
}
public static void main(String[] args) {
System.out.println(POINTS.byteSize()); // 24
System.out.println(offset(2, "y")); // 20
try (Arena arena = Arena.ofConfined()) {
MemorySegment seg = arena.allocate(POINTS);
for (int i = 0; i < 3; i++) {
seg.set(ValueLayout.JAVA_INT, offset(i, "x"), i);
seg.set(ValueLayout.JAVA_INT, offset(i, "y"), i * 10);
}
seg.elements(POINT).forEach(p ->
System.out.println(p.get(ValueLayout.JAVA_INT, 0)
+ "," + p.get(ValueLayout.JAVA_INT, 4)));
}
}
}The program prints 24, 20, and then 0,0, 1,10 and 2,20.
seg.elements(POINT) returns a stream of slices. Each slice is a MemorySegment view of exactly one struct, so offsets inside the lambda are relative to that element. Slices share memory with the parent. They do not copy it.
The diagram below shows how the three-point array is laid out in memory.
Unions and padding at the end
A unionLayout places all members at offset 0. Its size is the size of the largest member, and its alignment is the largest alignment. Use it for C unions:
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.UnionLayout;
import java.lang.foreign.ValueLayout;
public class UnionDemo {
static final UnionLayout NUMBER = MemoryLayout.unionLayout(
ValueLayout.JAVA_INT.withName("i"),
ValueLayout.JAVA_DOUBLE.withName("d"));
public static void main(String[] args) {
System.out.println(NUMBER.byteSize()); // 8
}
}A struct also needs trailing padding when its size must be a multiple of its alignment. Take struct { double d; char c; }. C makes it 16 bytes, so each element of an array of them stays aligned. In Java you must add paddingLayout(7) after the c member. If you leave it out, the size is 9 and an array of them will misalign every element after the first.
Matching the platform
Two traps follow from the fact that C types vary by platform.
longin C is 4 bytes on 64-bit Windows and 8 bytes on 64-bit Linux and macOS. Do not useJAVA_LONGfor it without checking.- A struct that the compiler packs or aligns differently needs a layout that matches. Check the header for
#pragma packor__attribute__((packed)). A packed layout is built withwithByteAlignment(1)on the members.
To get the correct layout for the current platform, ask the linker for its canonical layouts:
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
public class CanonicalDemo {
public static void main(String[] args) {
MemoryLayout cLong = Linker.nativeLinker().canonicalLayouts().get("long");
System.out.println(cLong.byteSize()); // 8 on Linux x64, 4 on Windows x64
}
}The map has keys such as "int", "long", "size_t" and "char". Using it is safer than assuming sizes, and it keeps the same layout code working across operating systems.
Common errors
- Missing padding. The symptom is an
IllegalArgumentExceptionwhile thestructLayoutis built. Fix it by addingpaddingLayoutwhere the C compiler would pad. - Wrong total size. Allocating by hand with
arena.allocate(16)and then using a 24-byte layout leads toIndexOutOfBoundsException. Allocate witharena.allocate(layout)so size and alignment come from one place. - Computing offsets in hot loops.
byteOffsetis cheap, but call it once and store the result in astatic final long. The examples above follow this pattern. - Assuming the layout reads the memory. A layout is only a description. It never checks that the bytes in a segment really hold that struct. If the layout is wrong, you read wrong values silently.
Exercises
Exercise
A C struct is declared as struct sample { int id; char flag; double score; }; on a 64-bit Linux platform. Write the Java StructLayout that matches it, including padding, and state its byte size and alignment.
Show answer
The int takes bytes 0-3 and the char is at byte 4. The double needs 8-byte alignment, so 3 bytes of padding follow the char and the double starts at offset 8. The layout is MemoryLayout.structLayout(ValueLayout.JAVA_INT.withName("id"), ValueLayout.JAVA_BYTE.withName("flag"), MemoryLayout.paddingLayout(3), ValueLayout.JAVA_DOUBLE.withName("score")). Its size is 16 bytes and its alignment is 8.
Exercise
You build SequenceLayout S = MemoryLayout.sequenceLayout(4, POINT), where POINT is the two-int struct from this chapter. What does S.byteOffset(PathElement.sequenceElement(3), PathElement.groupElement("x")) return, and what is S.byteSize()?
Show answer
Each POINT is 8 bytes, so element 3 starts at 3 8 = 24, and x is the first member, so the offset is 24. The total size is 4 8 = 32 bytes.