2

I am trying to pass a JavaScript array to a host function, but can find no documentation on how to do this using ClearScript. I would have expected it to be this simple, but it's not.

public class myHostType
{
    public static void print(string format, object[] args)
    {
        //TODO: implement print
    }
}
...
engine.addHostType("console", typeof(myHostType));
engine.Execute("console.print('Hello', ['World', 42])");

With this code I get Error: The best overloaded method match for V8SScript1.myHostType.print(string, object[])' has some invalid arguments.'

This is the closest thing I can find to a solution. Is there not a better way of doing this?

public class myHostType
{
    public static void print(string format, dynamic args)
    {
        var realArgs = new Object[args.length];
        for (int i = 0; i < realArgs.Length; ++i)
        {
            realArgs[i] = args[i];
        }
        //TODO: implement print
    }
}
Chris_F
  • 4,991
  • 5
  • 33
  • 63

1 Answers1

4

ClearScript doesn't convert arrays automatically, so you have to do it yourself, as you have.

You could also do the conversion on the script side:

engine.AddHostObject("host", new HostFunctions());
engine.Execute(@"
    Array.prototype.toClrArray = function () {
        var clrArray = host.newArr(this.length);
        for (var i = 0; i < this.length; ++i) {
            clrArray[i] = this[i];
        }
        return clrArray;
    };
");
...
engine.Execute("console.print('Hello {0} {1}', ['World', 42].toClrArray());");

In this case however it might make sense to use params:

public class myHostType {
    public static void print(string format, params object[] args) {
        Console.WriteLine(format, args);
    }
}
...
engine.Execute("console.print('Hello {0} {1}', 'World', 42);");
BitCortex
  • 3,328
  • 1
  • 15
  • 19