java 14 and JEP 370: Foreign-Memory Access API-- Array Of Bytes.

Ty Young youngty1997 at gmail.com
Wed Mar 25 15:58:01 UTC 2020


On 3/25/20 10:26 AM, Maurizio Cimadamore wrote:
> 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?


Going off of:


 >my question, using MemorySegment & VarHandle classes how to read/write 
array of bytes at one shot. not byte by byte.


and


 >Yes, I am aware of asByteBuffer(). but as per documentation the main 
reason for this new Memory Segment access is to avoid ByteBuffer class.


They seem to want a method that accepts an array of bytes(byte[]) which 
is then put into memory and then be able to get it back without 
accessing individual offset locations or using ByteBuffer.


There is no such thing for setting AFAIK. The MemorySegment.ofArray() 
methods just create a MemorySegment that can hold an array of the given 
array's size AFAIK.


There is a method for getting the array in bulk though: 
<MemorySegment>.toByteArray().




>
> 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