Layouts and Structs
Describe native memory layouts.
Layouts and Structs is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Describing Native Memory
Native data is rarely a single value. C uses structs, arrays, and unions. FFM models these shapes with memory layouts, letting you read and write structured native memory safely.
The Layout Family
The layout types form a small hierarchy:
ValueLayout: a primitive (int, long, double, address)SequenceLayout: a fixed-size array of a layoutStructLayout: fields laid out sequentiallyUnionLayout: overlapping fields
A Value Layout
The simplest layouts are the built-in value layouts. They carry size, alignment, and byte order.
import java.lang.foreign.ValueLayout;
public class Main {
public static void main(String[] args) {
System.out.println("int size: " + ValueLayout.JAVA_INT.byteSize());
System.out.println("double size: " + ValueLayout.JAVA_DOUBLE.byteSize());
}
}Defining a Struct
Model a C struct with MemoryLayout.structLayout(...), naming each field with withName. Consider C's struct Point { int x; int y; }.
import java.lang.foreign.*;
public class Main {
public static void main(String[] args) {
StructLayout point = MemoryLayout.structLayout(
ValueLayout.JAVA_INT.withName("x"),
ValueLayout.JAVA_INT.withName("y"));
System.out.println("Point size: " + point.byteSize());
}
}Var Handles for Fields
To read or write a named field, derive a VarHandle using a path expression. groupElement("x") selects the field by name.
import java.lang.foreign.*;
import java.lang.invoke.VarHandle;
public class Main {
public static void main(String[] args) {
StructLayout point = MemoryLayout.structLayout(
ValueLayout.JAVA_INT.withName("x"),
ValueLayout.JAVA_INT.withName("y"));
VarHandle xHandle = point.varHandle(
MemoryLayout.PathElement.groupElement("x"));
System.out.println("Built VarHandle for x: " + xHandle);
}
}Reading and Writing a Struct
Allocate a segment sized to the layout, then use the var handles to set and get fields. This mirrors filling a C struct.
import java.lang.foreign.*;
import java.lang.invoke.VarHandle;
public class Main {
public static void main(String[] args) {
StructLayout point = MemoryLayout.structLayout(
ValueLayout.JAVA_INT.withName("x"),
ValueLayout.JAVA_INT.withName("y"));
VarHandle xh = point.varHandle(MemoryLayout.PathElement.groupElement("x"));
VarHandle yh = point.varHandle(MemoryLayout.PathElement.groupElement("y"));
try (Arena arena = Arena.ofConfined()) {
MemorySegment p = arena.allocate(point);
xh.set(p, 0L, 3);
yh.set(p, 0L, 4);
System.out.println("Point = (" + xh.get(p, 0L) + ", " + yh.get(p, 0L) + ")");
}
}
}Padding and Alignment
C compilers insert padding so fields are aligned. FFM does not add it automatically, so you must include MemoryLayout.paddingLayout(n) to match the C layout exactly.
Getting alignment wrong corrupts every field after the gap.
Explicit Padding Example
For struct { char c; int n; }, the int must align to 4 bytes, so 3 padding bytes follow the char.
import java.lang.foreign.*;
public class Main {
public static void main(String[] args) {
StructLayout s = MemoryLayout.structLayout(
ValueLayout.JAVA_BYTE.withName("c"),
MemoryLayout.paddingLayout(3),
ValueLayout.JAVA_INT.withName("n"));
System.out.println("Aligned struct size: " + s.byteSize());
}
}Sequence Layouts
A SequenceLayout describes an array. MemoryLayout.sequenceLayout(count, element) models, say, an array of 10 doubles.
import java.lang.foreign.*;
public class Main {
public static void main(String[] args) {
SequenceLayout arr = MemoryLayout.sequenceLayout(10, ValueLayout.JAVA_DOUBLE);
System.out.println("Array bytes: " + arr.byteSize());
}
}Nested Layouts
Layouts compose. A struct can contain a sequence, and a sequence can contain structs. Path expressions like sequenceElement() and groupElement(name) navigate deep into nested data.
This handles real-world C data structures of arbitrary complexity.
Offsets and Slicing
You can query a field's byteOffset from its path and use segment.asSlice(offset, size) to obtain a sub-segment, useful for passing one field of a struct to a native function.
Quick Check
Recall a common pitfall with structs.
Recap
You learned to describe native data:
- Layout family:
ValueLayout,SequenceLayout,StructLayout,UnionLayout - Name fields with
withName; access viaVarHandleand path elements - Add explicit
paddingLayoutfor correct alignment - Compose nested layouts and slice with
asSlice
That completes the Foreign Function and Memory API course.
Frequently asked questions
Is the “Layouts and Structs” lesson free?
Yes — the full text of “Layouts and Structs” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Layouts and Structs”?
Describe native memory layouts. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Layouts and Structs” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Why FFM over JNI
- MemorySegment and Arena
- Downcall Handles
- Layouts and Structs