Hi,
I have a question concerning "custom" classes used in engine.AddHostType. I add custom classes and their respective methods to the scripting, such that the user cann reach my functions e.g. using syntax like customStuff.DoSomething() etc. That is very powerful thing and works just fine. I was only wondering if it was possible to add those functions such that the user doesn't have to bother withthe "customStuff" prefix, such that he could invoke "DoSomething" directly?
Thanks and keep up with this great lib!
Hi @flat-eric147,
There are many ways to get the desired result. Suppose your custom class looks like this:
``` C#
public static class CustomStuff {
public static void DoSomething() {
Console.WriteLine("I just did something.");
}
public static string DoSomethingElse(int count) {
return string.Format("I just did something else {0} times.", count);
}
}
First, you could use [`HostItemFlags.GlobalMembers`](https://microsoft.github.io/ClearScript/Reference/html/T_Microsoft_ClearScript_HostItemFlags.htm) to expose all members in the root namespace:
``` C#
engine.AddHostType(HostItemFlags.GlobalMembers, typeof(CustomStuff));
This way CustomStuff remains exposed, but DoSomething() becomes an alias for CustomStuff.DoSomething() and so on. Note that this applies to all members, not just methods.
Another possibility is to expose individual delegates:
``` C#
engine.Script.DoSomething = new Action(CustomStuff.DoSomething);
engine.Script.DoSomethingElse = new Func
You could also use a script function to set up an API of your choice. Here's a simple example:
``` C#
dynamic installApi = engine.Evaluate(@"
(function (CustomStuff) {
DoSomething = CustomStuff.DoSomething;
DoSomethingElse = CustomStuff.DoSomethingElse;
}).valueOf()
");
installApi(typeof(CustomStuff).ToHostType(engine));
These are just a few ideas; hopefully they give you a sense of what's possible.
Good luck!
Thank you, that's brilliant, exactly what I was looking for!