java 14 and JEP 370: Foreign-Memory Access API-- Array Of Bytes.
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Wed Mar 25 15:26:29 UTC 2020
Hi,
your example is almost correct, the problem is in your cast:
byte value[] = (byte[]) byteHandle.get(address.addOffset(0));
This should be:
byte value = (byte) byteHandle.get(address.addOffset(0));
That is, you read one byte at a time.
Does this help?
Thanks
Maurizio
On 25/03/2020 15:02, Ahmed Hamdallah 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