Skip to content

Instantly share code, notes, and snippets.

@mcimadamore
Created June 3, 2022 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcimadamore/424fcfc6ad36a8d4de322bc5f707c98b to your computer and use it in GitHub Desktop.
Save mcimadamore/424fcfc6ad36a8d4de322bc5f707c98b to your computer and use it in GitHub Desktop.
Example of struct access with layouts and heap segments
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SequenceLayout;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.VarHandle;
public class Test {
static final ValueLayout.OfChar JAVA_CHAR_UNALIGNED = ValueLayout.JAVA_CHAR.withBitAlignment(8);
static final ValueLayout.OfInt JAVA_INT_UNALIGNED = ValueLayout.JAVA_INT.withBitAlignment(8);
public static void main(String[] args) {
// a layout
SequenceLayout tagValues = MemoryLayout.sequenceLayout(
5, MemoryLayout.structLayout(
JAVA_CHAR_UNALIGNED.withName("tag"),
JAVA_INT_UNALIGNED.withName("value"))
);
// a var handle to read all the fields "tag"
VarHandle handle_tag = tagValues.varHandle(
MemoryLayout.PathElement.sequenceElement(),
MemoryLayout.PathElement.groupElement("tag"));
// a var handle to read all the fields "value"
VarHandle handle_value = tagValues.varHandle(
MemoryLayout.PathElement.sequenceElement(),
MemoryLayout.PathElement.groupElement("value"));
// create an heap segment that is big enough
MemorySegment segment = MemorySegment.ofArray(new byte[(int)tagValues.byteSize()]);
// create some values
char[] tags = { 'a', 'b', 'c', 'd', 'e' };
int[] values = { 1, 2, 3, 4, 5 };
// set the values into the segment
for (int i = 0 ; i < tagValues.elementCount() ; i++) {
handle_tag.set(segment, (long)i, tags[i]);
handle_value.set(segment, (long)i, values[i]);
}
// print the struct fields
for (int i = 0 ; i < tagValues.elementCount() ; i++) {
char tag = (char)handle_tag.get(segment, (long)i);
int value = (int)handle_value.get(segment, (long)i);
System.out.printf("Struct #%d = { tag = %c ; value = %d } \n", i, tag, value);
}
}
}
@leerho
Copy link

leerho commented Jun 4, 2022

Apparently, this code requires JDK18. Is there a way to do the same with JDK17?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment