Javascript side create byte array

Mar 10, 2016 at 12:56 PM
Hi Guys, this is a simple issue but I cannot get it to work. I need to create a byte array on the javascript side but I´m getting the following error depending on the type I use:

byte is not a function


I´ve tried the following:

var message = new byte[4096];
var message = new System.Byte[4096];
var message = host.newVar(System.Byte[4096]);

Obviously I am doing something wrong and clearscript works differentrly with arrays.

Can someone help me?. Thanks.
Mar 10, 2016 at 1:08 PM
Also tried:

var message = new host.newArr(byte, 4096);
var message = new host.newArr(System.Byte, 4096);

But I get 'Invalid constructor invocation'
Mar 10, 2016 at 2:11 PM
Sorry, my mistake.... the correct line was:

var message = host.newArr(System.Byte, 4096);
Marked as answer by nicoriff on 3/10/2016 at 7:12 AM
Coordinator
Mar 10, 2016 at 2:42 PM
Hello,

Yes, that's probably the most generic and straightforward way to do it. And if you'd prefer not to expose HostFunctions or the array element type, you could always provide a custom array factory for your scenario.

Cheers!
Coordinator
Mar 10, 2016 at 6:04 PM
Hi again,

By the way, if you're using V8 for heavy-duty byte array manipulation in JavaScript, consider using Uint8Array. Doing so should provide an enormous performance advantage over using a managed array from script code, and ClearScript (since Version 5.4.4) supports fast data transfer between managed arrays and JavaScript typed arrays.

Good luck!
Mar 11, 2016 at 6:02 PM
What I´m doing is passing the array as parameter to a c# method that is awaiting for a byte array. Do you think that if I use Uint8Array that can be mapped into a byte array on the c# side?.

Thanks.
Coordinator
Mar 11, 2016 at 8:22 PM
Hi nicoriff,

There's no automatic mapping; you'd have to convert the Uint8Array array to System.Byte[] explicitly. Recent ClearScript versions provide a fast API for that.

As for which array type to use, that depends on which side is doing most of the array access. If the answer is "both", and if we're talking about a large array, then explicit conversion might be the best option.

Cheers!
Apr 15, 2016 at 11:17 AM
Hello,

I'd like to use the new API for converting between byte[] and Uint8Array but I can't find any documentation. What do I need to do?
Coordinator
Apr 15, 2016 at 12:29 PM
Hi ZoneRunner,

Here's a sample:
// using Microsoft.ClearScript.JavaScript;
engine.Execute("values = new Uint8Array([1, 2, 3, 4, 5])");
var values = (ITypedArray<byte>)engine.Script.values;
Console.WriteLine(string.Join(", ", values.ToArray()));
The ITypedArray interface also has methods for transferring array elements to and from existing .NET arrays.

Good luck!
Apr 15, 2016 at 12:55 PM
Thanks :)