MemorySegment.ofAddress(...).reinterpret(...)

Jorn Vernee jorn.vernee at oracle.com
Wed Jul 5 23:12:41 UTC 2023


Hello,

The usual way of attaching a size to a memory segment would be through a 
target address layout [1]. MS::reinterpret is meant for cases where the 
layout of the pointee is not statically known (and can not be captured 
with a memory layout). But, both cases assume you're reading/writing 
MemorySegments directly, instead of going through longs. Are neither of 
these an option for you? Could you explain your use case a bit more?

I think we briefly considered having multiple MS::ofAddress overloads. 
IIRC we decided against it, because the current MS::ofAddress is not a 
restricted method, but, an overload that sets the size of the returned 
segment would need to be restricted since the segment would be 
accessible. So, adding more overloads would create a split between them 
in terms of restricted-ness, which is not great.

I'll also note that, someone could define a utility method that fuses 
the two operations, e.g.:

static MemorySegment longToSizedSegment(long baseAddress, long byteSize) {
     return MemorySegment.ofAddress(baseAddress).reinterpret(byteSize);
}

That is to say: I think we have the right primitives available in the 
API. Though, your experience is a useful data point. We might want to 
add some useful methods in the future if we see enough demand for them.

Thanks,
Jorn

[1]: 
https://download.java.net/java/early_access/jdk21/docs/api/java.base/java/lang/foreign/AddressLayout.html#withTargetLayout(java.lang.foreign.MemoryLayout)

On 06/07/2023 00:19, Brian S O'Neill wrote:
> I'm converting one of my projects from Unsafe to java.lang.foreign, 
> and one thing that I find annoying is the two step process for 
> defining a MemorySegment which refers to an arbitrary address. I call 
> reinterpret every single time, which is both tedious and error prone. 
> I've forgotten to do this a few times, and the resulting exception is 
> quite confusing at first.
>
> It would be nice of the ofAddress method was overloaded to accept a 
> length. Code that uses it becomes smaller, and it skips the extra 
> object allocation which may or may not be eliminated by escape analysis.


More information about the panama-dev mailing list