casting typed array to java byte[] is it possible?

Sundararajan Athijegannathan sundararajan.athijegannathan at oracle.com
Fri Oct 12 12:04:45 UTC 2018


Hi Paulo Lopes,

ArrayBuffer can be created using a nio ByteBuffer.

// you could create a ByteBuffer in Java & pass
var bb = java.nio.ByteBuffer.allocateDirect(100)

// create JS ArrayBuffer backed by Java ByteBuffer instance
var ab = new ArrayBuffer(bb)

var ia = new Int8Array(ab)
ia[0] = 10
print(bb.get(0))

Hope this helps,
-Sundar

On 12/10/18, 5:04 PM, Paulo Lopes wrote:
> Hi Hannes,
>
> Thanks for the tip, knowing that the convention isn't possible as is, are there any alternatives to get the JVM buffer that backs a typed array?
>
> I wanted to perform some work on a given buffer and then pass it to the JVM for further processing. Having to copy the buffer byte by byte will introduce a penalty that kind of defeats the whole purpose of using typed arrays to start with.
>
>
> Paulo Lopes
> Principal Software Engineer
>
>
>    Original Message  
> From: hannes.wallnoefer at oracle.com
> Sent: October 12, 2018 10:10 AM
> To: pmartins at redhat.com
> Cc: nashorn-dev at openjdk.java.net
> Subject: Re: casting typed array to java byte[] is it possible?
>
> Hi Paulo,
>
> Java.to() would be the way to go, but as you found out it does not support typed arrays.
>
> What works is to convert the typed array to an ordinary JS array and convert to byte[] from there:
>
>    Java.to(Array.prototype.slice.call(arr), 'byte[]‘);
>
> That’s obviously not very elegant nor efficient, but it’s the only workaround I can think of.
>
> Hannes
>
>
>> Am 11.10.2018 um 20:21 schrieb Paulo Lopes<pmartins at redhat.com>:
>>
>> Hi,
>>
>> I'm trying to handle a case where a Uint8Array is being passed to a
>> method, that has the signature:
>>
>> String encode(byte[]);
>>
>> Sadly nashorn fails with:
>>
>> java.lang.ClassCastException: Cannot cast
>> jdk.nashorn.internal.objects.NativeUint8Array to [B
>>
>> And trying to help the cast with:
>>
>> javaObj.encode(Java.to(arr, 'byte[]'));
>>
>> Does not help either. The documentation on typed arrays is quite scarce
>> so I cannot see how to handle this, does anyone have a clue?
>>
>> Thanks!
>> Paulo
>>


More information about the nashorn-dev mailing list