java 14 and JEP 370: Foreign-Memory Access API-- Array Of Bytes.
Henry Jen
henry.jen at oracle.com
Wed Mar 25 15:30:10 UTC 2020
For primitive types, you can use the combination of MemoryAddress.copy and MemorySegment.ofArray.
MemoryAddress.copy(MemorySegment.ofArray(byteArrayString).baseAddress(), address, byteArrayString.length);
Cheers,
Henry
> On Mar 25, 2020, at 8:02 AM, Ahmed Hamdallah <ahmdprog at gmail.com> wrote:
>
> hello,
>
> Regarding java 14 new feature of new Foreign-Memory API. it is actually bit complicated for me regarding classes SequenceLayout & VarHandle.
>
> since it is a new feature, i could not find many example to access MemorySegment data.
>
> my question, using MemorySegment & VarHandle classes how to read/write array of bytes at one shot. not byte by byte.
>
> Yes, I am aware of asByteBuffer(). but as per documentation the main reason for this new Memory Segment access is to avoid ByteBuffer class.
>
> this is example
>
> byte[] bytesArrayString = "Hello MemorySegment".getBytes();
>
> MemoryAddress address = MemorySegment.allocateNative(4096).baseAddress();
>
> SequenceLayout bytes = MemoryLayout.ofSequence(bytesArrayString.length, MemoryLayouts.JAVA_BYTE);
>
> VarHandle byteHandle = bytes.varHandle(byte.class, MemoryLayout.PathElement.sequenceElement());
>
> byteHandle.set(address.addOffset(0), (byte[]) bytesArrayString);
>
> byte value[] = (byte[]) byteHandle.get(address.addOffset(0));
>
> System.out.println("Memory Value: " + value.length + new String(value));
>
> error
>
> java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(VarHandle,MemoryAddressProxy,long,byte)void to (VarHandle,MemoryAddress,long,byte[])void
> java<https://stackoverflow.com/questions/tagged/java>
More information about the panama-dev
mailing list