Obtain MemorySegment from MemoryAddress for a given MemoryLayout
Jorn Vernee
jorn.vernee at oracle.com
Mon Jan 4 10:46:26 UTC 2021
Hi,
On 28/12/2020 19:15, Sebastian Stenzel wrote:
> During my latest experiments with Panama, I have to deal a lot with MemoryAddresses pointing to structs, that I need to access from Java:
>
> Let's say I have demo.h declaring my_struct:
>
> ```
> struct my_struct {
> int foo;
> };
>
> ```
>
> If I run jextract on demo.h, it'll generate code that allows me to get "foo" from a segment, but not from an address:
>
> ```
> int getFooFromMyStruct(MemoryAddress addr) {
> var segment = demo_h.my_struct.ofAddressRestricted(addr); // is there a better way, if I know the layout for sure?
> return demo_h.my_struct.foo$get(segment); // segment required here
> }
> ```
>
> Now I'm wondering, if there is any safe (read: not restricted) way to obtain a MemorySegment for a given layout and address?
No, there is no non-restricted variant for turning a MemoryAddress into
a MemorySegment. The latter is directly dereferencable from Java (hence
that being the required type for the getter), while the former is not.
The conversion from a MemoryAddress to a MemorySegment needs to
essentially attach a size to a pointer to define a region of
dereferencable memory, but there is no way to mechanically check that
the size being attached is actually correct. So, dereferencing the
resulting MemorySegment can still result in crashes and/or silent memory
corruption, and hence it is restricted functionality.
Jorn
More information about the panama-dev
mailing list