Created
June 3, 2022 21:49
-
-
Save mcimadamore/424fcfc6ad36a8d4de322bc5f707c98b to your computer and use it in GitHub Desktop.
Example of struct access with layouts and heap segments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Apparently, this code requires JDK18. Is there a way to do the same with JDK17?