Sub topic 4
Value layouts: describing ints, longs and pointers
This chapter assumes you have read the earlier chapters on memory segments and arenas. You should be able to allocate a MemorySegment from an Arena and know that a segment is a bounded view of memory. Basic C knowledge (fixed-size integers, pointers, alignment) is also assumed.
Why layouts exist
A MemorySegment is only bytes. Nothing in it says whether bytes 0 to 3 hold an int, a float, or half of a long. In C, the compiler decides that from declared types. In the FFM API you state it yourself, every time you touch memory, by passing a value layout.
A value layout describes one primitive value in memory. It carries three facts:
- The size in bytes.
- The alignment, which is the address multiple at which the value must be stored.
- The byte order (endianness).
Each layout also names a Java carrier type, the Java type the value is read into or written from. The get and set methods on MemorySegment take a layout and choose the matching Java type, so get(ValueLayout.JAVA_INT, 0) returns an int.
The built-in layouts
java.lang.foreign.ValueLayout declares one constant per primitive, using the platform's native byte order.
| Layout | Carrier type | Size in bytes | Typical C counterpart |
|---|---|---|---|
| `JAVA_BYTE` | `byte` | 1 | `char`, `int8_t` |
| `JAVA_BOOLEAN` | `boolean` | 1 | `_Bool` |
| `JAVA_SHORT` | `short` | 2 | `short`, `int16_t` |
| `JAVA_CHAR` | `char` | 2 | no C equivalent (UTF-16 unit) |
| `JAVA_INT` | `int` | 4 | `int`, `int32_t` |
| `JAVA_LONG` | `long` | 8 | `long long`, `int64_t` |
| `JAVA_FLOAT` | `float` | 4 | `float` |
| `JAVA_DOUBLE` | `double` | 8 | `double` |
| `ADDRESS` | `MemorySegment` | 4 or 8 | any pointer such as `void *` |
The table says "typical" because C types are defined by the platform, not by the language. int is 4 bytes on every mainstream platform, but long is 8 bytes on 64-bit Linux and macOS and 4 bytes on 64-bit Windows. JAVA_LONG is always 8 bytes. If a C signature says long, JAVA_LONG is correct on Linux and wrong on Windows.
Some libraries need a layout that matches the platform's C types exactly. Linker.nativeLinker().canonicalLayouts() returns a map from names such as "int", "long" and "size_t" to the layout for the current platform. The sections on function descriptors and platform pitfalls use it.
Reading and writing with layouts
The pattern is always segment.get(layout, offset) and segment.set(layout, offset, value). The offset is in bytes from the start of the segment.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class LayoutBasics {
public static void main(String[] args) {
System.out.println("JAVA_INT: size=" + ValueLayout.JAVA_INT.byteSize()
+ " align=" + ValueLayout.JAVA_INT.byteAlignment());
System.out.println("JAVA_LONG: size=" + ValueLayout.JAVA_LONG.byteSize()
+ " align=" + ValueLayout.JAVA_LONG.byteAlignment());
System.out.println("ADDRESS: size=" + ValueLayout.ADDRESS.byteSize());
try (Arena arena = Arena.ofConfined()) {
MemorySegment seg = arena.allocate(16, 8);
seg.set(ValueLayout.JAVA_INT, 0, 7);
seg.set(ValueLayout.JAVA_LONG, 8, 1_000_000_000_000L);
System.out.println(seg.get(ValueLayout.JAVA_INT, 0)); // 7
System.out.println(seg.get(ValueLayout.JAVA_LONG, 8)); // 1000000000000
}
}
}On a 64-bit JVM this prints sizes 4, 8 and 8, with alignments 4 and 8. Nothing stops you from reading the same bytes with a different layout. Reading offset 0 with JAVA_FLOAT would return the bit pattern of 7 reinterpreted as a float, with no error. The layout you pass is the only type information there is.
Indexed access
For arrays, getAtIndex and setAtIndex multiply the index by the layout's size. This avoids writing i * 4 by hand.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class IndexedAccess {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment ints = arena.allocate(5 * ValueLayout.JAVA_INT.byteSize(),
ValueLayout.JAVA_INT.byteAlignment());
for (int i = 0; i < 5; i++) {
ints.setAtIndex(ValueLayout.JAVA_INT, i, i * i);
}
System.out.println(ints.getAtIndex(ValueLayout.JAVA_INT, 4)); // 16
}
}
}getAtIndex(JAVA_INT, 4) reads the same bytes as get(JAVA_INT, 16).
Alignment
Hardware can read an aligned value faster, and some platforms fault on a misaligned read. The API therefore checks alignment on every access. An access is legal only if the address of the accessed bytes is a multiple of the layout's alignment. The built-in layouts use natural alignment, so a JAVA_INT access must land on a 4-byte boundary.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class AlignmentDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment seg = arena.allocate(16, 8);
try {
seg.get(ValueLayout.JAVA_INT, 1); // address is not a multiple of 4
} catch (IllegalArgumentException e) {
System.out.println("misaligned access rejected");
}
// The unaligned variant has alignment 1 and accepts any offset.
seg.set(ValueLayout.JAVA_INT_UNALIGNED, 1, 99);
System.out.println(seg.get(ValueLayout.JAVA_INT_UNALIGNED, 1)); // 99
}
}
}Every constant has an _UNALIGNED twin, such as JAVA_LONG_UNALIGNED. Use these for packed data, for example a network buffer with a 4-byte field at offset 1. Do not use them to silence an alignment error without finding out why the offset is odd. Usually the cause is a wrong offset or a missing struct padding field.
The alignment you request when allocating matters as well. arena.allocate(16, 8) guarantees an 8-byte-aligned base address. If you allocate with a smaller alignment, accesses with wider layouts may fail even when the offset looks correct.
Byte order
Native byte order on x86-64 and most ARM systems is little-endian. Network protocols and many file formats use big-endian. Call withOrder to get a layout with a different order. Layouts are immutable, so this returns a new object.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.ByteOrder;
public class ByteOrderDemo {
public static void main(String[] args) {
ValueLayout.OfInt big = ValueLayout.JAVA_INT.withOrder(ByteOrder.BIG_ENDIAN);
ValueLayout.OfInt little = ValueLayout.JAVA_INT.withOrder(ByteOrder.LITTLE_ENDIAN);
try (Arena arena = Arena.ofConfined()) {
MemorySegment seg = arena.allocate(ValueLayout.JAVA_INT);
seg.set(big, 0, 0x01020304);
System.out.println(seg.get(ValueLayout.JAVA_BYTE, 0)); // 1, the most significant byte first
System.out.println(seg.get(little, 0)); // 67305985, which is 0x04030201
}
}
}Both lines print the same on every platform, because the order is stated explicitly. Use native order when exchanging data with C code in the same process. Use an explicit order only for data that has a defined wire or file format.
Pointers and ADDRESS
ValueLayout.ADDRESS describes a pointer. It is an AddressLayout, and its carrier type is MemorySegment. Its size is the platform's pointer size, 8 bytes on a 64-bit JVM.
A pointer read from memory has no known size. The API cannot tell whether a char * points at 1 byte or 1 MB, so the segment it returns has length 0. Any access through it fails.
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
public class AddressDemo {
public static void main(String[] args) {
try (Arena arena = Arena.ofConfined()) {
MemorySegment target = arena.allocate(ValueLayout.JAVA_INT);
target.set(ValueLayout.JAVA_INT, 0, 123);
MemorySegment slot = arena.allocate(ValueLayout.ADDRESS);
slot.set(ValueLayout.ADDRESS, 0, target);
MemorySegment ptr = slot.get(ValueLayout.ADDRESS, 0);
System.out.println(ptr.address() == target.address()); // true
System.out.println(ptr.byteSize()); // 0
}
}
}The zero-length segment is a safety feature. The JVM will not let you read through a raw pointer it knows nothing about. To read through it you must assert a size. There are two ways to do this:
MemorySegment.reinterpret(long size)returns a view of the same address with the size you claim.ADDRESS.withTargetLayout(layout)makes every segment read through that layout automatically have the size oflayout.
Both are restricted methods. They need native access enabled, which the chapter on restricted methods covers. They are restricted because you are promising the JVM something it cannot check. If the claim is wrong, the JVM can crash.
Layouts in the next chapters
You will use these same layouts in three places later in the tutorial:
- Struct and sequence layouts are built by combining value layouts, with padding to satisfy alignment.
- A function descriptor lists the value layouts of a C function's return and parameter types.
- Callback and downcall handles convert between the carrier types and native values using those descriptors.
A layout that is wrong in one of these places fails in the same way as above: silently or with a crash.
Common errors
- Misaligned access. An
IllegalArgumentExceptionfromgetorsetmeans the address is not a multiple of the layout's alignment. Check the offset, the allocation alignment, and any struct padding. - Wrong size for
long. UsingJAVA_LONGfor a Clongworks on Linux and macOS but not on Windows. UsecanonicalLayouts().get("long")or fixed-width types such asint64_t. - Reading through a zero-length pointer. An
IndexOutOfBoundsExceptionon a segment returned fromADDRESSmeans you did not give it a size. - Treating
JAVA_CHARas Cchar. It is 2 bytes. UseJAVA_BYTEfor Cchar. - Forgetting byte order. A value that looks scrambled when it is read back usually means the producer and consumer used different orders.
Exercise
A C library declares void fill(int *out, long count) and you run on 64-bit Windows. Which value layouts describe the two parameters, and what is wrong with using ValueLayout.JAVA_LONG for count?
Show answer
out is a pointer, so it uses ValueLayout.ADDRESS. count is a C long, which is 4 bytes on 64-bit Windows, so it needs a 4-byte layout, that is ValueLayout.JAVA_INT. The portable way to get the right layout is Linker.nativeLinker().canonicalLayouts().get("long"). JAVA_LONG is always 8 bytes, so on Windows the call would pass 8 bytes where the callee expects 4, and the value would be read incorrectly.
Exercise
You allocate MemorySegment seg = arena.allocate(16, 8) and call seg.get(ValueLayout.JAVA_LONG, 4). What happens, and what are two ways to fix it?
Show answer
It throws IllegalArgumentException, because offset 4 gives an address that is not a multiple of 8, the alignment of JAVA_LONG. One fix is to read at an offset that is a multiple of 8, such as 0 or 8. The other is to use ValueLayout.JAVA_LONG_UNALIGNED if the data really is packed that way.