Slice a MemorySegment using SequenceLayout's element boundaries
Sebastian Stenzel
sebastian.stenzel at gmail.com
Tue Jan 11 20:48:15 UTC 2022
Hi,
I've just updated some of my experiments [1] using the latest API in the upcoming JDK 18. Which lead to a question:
Given:
1. a MemoryAddress (parameter in an upcall stub) representing a pointer to an array of structs
2. a matching SequenceLayout of GroupLayouts for this array of structs
Is there any convenient API to obtain a MemorySegment of the nth array element? Currently I'm calculating memory boundaries manually and slice my segment accordingly:
```
private void upcall(MemoryAddress pointer) {
try (var scope = ResourceScope.newConfinedScope()) {
var structLayout = ...;
var sequenceLayout = MemoryLayout.sequenceLayout(42, structLayout);
var segment = MemorySegment.ofAddress(pointer, sequenceLayout.byteSize(), scope);
// either:
var offset0 = sequenceLayout.byteOffset(MemoryLayout.PathElement.sequenceElement(0));
var offset1 = sequenceLayout.byteOffset(MemoryLayout.PathElement.sequenceElement(1));
var elem0 = segment.asSlice(offset0, structLayout.byteSize());
var elem1 = segment.asSlice(offset1, structLayout.byteSize());
// or alternatively:
var elem0 = segment.asSlice(0, structLayout.byteSize());
var elem1 = segment.asSlice(structLayout.byteSize(), structLayout.byteSize());
}
}
```
But since a SequenceLayout knows how to calculate the offset and knows the size of each of its elements, I guess there is a more convenient way to slice a segment.
Or if there isn't: Consider this a feature request
Cheers!
Sebastian
[1]: https://github.com/skymatic/fuse-panama/blob/develop/mac/src/main/java/de/skymatic/fusepanama/mac/MacFuseOperationsMapper.java#L178-L187
More information about the panama-dev
mailing list