To call script function print in the below example, I just embed the parameter in the script text "print('Hello, Wolrd!')". However, what should I do if I need to pass a big byte array?
using Microsoft.ClearScript.V8;
using System;
namespace ClearScriptDemo
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
using (var engine = new V8ScriptEngine())
{
engine.AddHostType("Console", typeof(Console));
engine.Execute("function print(x) { Console.WriteLine(x); }");
engine.Execute("print('Hello, Wolrd!')");
}
Console.ReadKey();
}
}
}
Hi @tu-lehong,
To call script function print in the below example, I just embed the parameter in the script text "print('Hello, Wolrd!')".
That's one way to do it, but we recommend that you avoid invoking the JavaScript parser whenever possible. In this case, once you've created the script function, you can call it directly and pass in any argument you wish:
``` C#
engine.Script.print("Greetings!");
This approach delivers better performance and facilitates script debugging.
>However, what should I do if I need to pass a big byte array?
In most cases, arrays don't require special handling. You can pass them into script functions just like any other data. Other than `Length` vs. `length`, JavaScript code can use a .NET array just like any other array-like object.
However, with large arrays performance can become an issue. Indexing into a .NET array from script code involves a round trip to the .NET side, which is another thing you'll want to minimize if you're concerned about performance.
For large binary data, we recommend that you use a [JavaScript typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). The host can transfer data from a .NET array to a typed array very quickly. Here's an example:
``` C#
// using Microsoft.ClearScript.JavaScript
// make a reusable script function for creating byte arrays
dynamic createJsByteArray = engine.Evaluate(@"
(function (length) {
return new Uint8Array(length);
}).valueOf()
");
// prepare .NET byte array
var bytes = new byte[4096];
new Random().NextBytes(bytes);
// create script byte array
var array = (ITypedArray<byte>)createJsByteArray(bytes.Length);
// transfer data to script byte array
array.Write(bytes, 0, Convert.ToUInt64(bytes.Length), 0);
// pass script byte array to script function
engine.Script.doSomething(array);
Good luck!
Thank you!