yantrajs / yantra

JavaScript Engine for .NET Standard
https://yantrajs.com
Apache License 2.0
199 stars 7 forks source link

ClrProxy documentation #71

Closed adiamante closed 1 year ago

adiamante commented 1 year ago

The documentation on ClrProxy was outdated but I was able to figure out how use it. The following is an example.

using YantraJS.Core;
using YantraJS.Core.Clr;

var synchronizationContext = new SynchronizationContext();
var context = new JSContext(synchronizationContext);

var calculator = new Calculator();
context["calculator"] = ClrProxy.From(calculator);

var a0 = await context.ExecuteAsync("calculator.add(1,1)");                 // a0 = {2} JSNumber
var a1 = await context.ExecuteAsync("await calculator.addAsync(1,1);");     // a1 = {2} JSNumber

public class Calculator
{
    public int Add(int x, int y)
    {
        return x + y;
    }

    public Task<int> AddAsync(int x, int y)
    {
        return Task.FromResult(x + y);
    }
}
ackava commented 1 year ago

@adiamante ClrProxy might be removed or will be changed, the correct way to supply Clr object would be to implement IJavaScriptObject or inheirt JavaScriptObject class. You can control what to export by using JSExport attribute. ClrProxy exports everything. I will be updating documentation soon.

Also using signature JSValue Method(in Arguments a) will be faster compared to using Clr types as arguments as there will be extra checks to convert JSValue to clr types. You can check this unit test on how to use it.

https://github.com/yantrajs/yantra/blob/main/YantraJS.Core.Tests/ClrObjects/CustomObject.cs

adiamante commented 1 year ago

@ackava Thanks. That was informative