153. Shaping C-like structs into memory segments
Let’s consider the C-like struct from the following figure:
Figure 7.13: A C-like structure
So, in Figure 7.13, we have a C-like struct named point
to shape an (x, y) pair of double
values. Moreover, we have 5 such pairs declared under the name pointarr
. We can try to shape a memory segment to fit this model as follows (arena
is an instance of Arena
):
MemorySegment segment = arena.allocate(
2 * ValueLayout.JAVA_DOUBLE.byteSize() * 5,
ValueLayout.JAVA_DOUBLE.byteAlignment());
Next, we should set (x, y) pairs into this segment. For this, we can visualize it as follows:
Figure 7.14: Memory segment to store (x, y) pairs
Based on this diagram, we can easily come up with the following snippet of code for setting the (x, y) pairs:
for (int i = 0; i < 5; i++) {
segment.setAtIndex(
ValueLayout.JAVA_DOUBLE, i * 2, Math.random());
segment.setAtIndex(
ValueLayout.JAVA_DOUBLE, i *...