microsoft / ClearScript

A library for adding scripting to .NET applications. Supports V8 (Windows, Linux, macOS) and JScript/VBScript (Windows).
https://microsoft.github.io/ClearScript/
MIT License
1.74k stars 148 forks source link

HostDelegate function with array parameter and call it with `apply` #497

Closed JangoBoogaloo closed 1 year ago

JangoBoogaloo commented 1 year ago

I am trying to delegate Path.Combine method into javascript and I am not able to call the method with apply. Can I get some hint for how to delegate array parameter method?

engine.AddHostObject("__path__combine", HostItemFlags.GlobalMembers, new Func<string[], string>(Path.Combine));
engine.Execute("var x = ['a', 'b', 'c']; __path__combine.apply(x)");
ClearScriptLib commented 1 year ago

Hi @JangoBoogaloo,

Instead of using Func, you can define a delegate type that captures Path.Combine's support for parameter arrays:

private delegate string PathCombine(params string[] args);

Now you can achieve the desired result via JavaScript's spread syntax:

engine.AddHostObject("__path__combine", new PathCombine(Path.Combine));
engine.Execute("var x = ['a', 'b', 'c']; __path__combine(...x)");

Good luck!

JangoBoogaloo commented 1 year ago

It works as expected. Thanks!