6

I'm making my backend on C# and frontend on JS.
I want to reuse some alghoritms written in C# in browser JavaScript.
Simplified example:

    class Fibonacci {
        int Fib(int x) {
            if (x == 0) return 0;
            int prev = 0;
            int next = 1;
            for (int i = 1; i < x; i++)
            {
                int sum = prev + next;
                prev = next;
                next = sum;
            }
           return next;
    }

Is it possible to compile one library-independent class to WebAssembly and use it from browser? How?

7

3 Answers 3

1

Yes, with NativeAOT-LLVM (https://github.com/dotnet/runtimelab/tree/feature/NativeAOT-LLVM). There's a similar question with a full answer at Compiling C# project to WebAssembly

-1

From what I understand, C# needs some middleware / framework to convert it to wasm. If your use case does not warrant Blazor, you might try the UNO platform: https://github.com/unoplatform/Uno.Wasm.Bootstrap

2
-5

You can call .NET methods form JavaScript functions like this

Here is the razor html

@inject IJSRuntime JS

<button @onclick=@CallToJS >Call JS function</button>

Here is the code behind

 @code {
    /// <summary>
    /// This method calls javascript function with .net object reference parameter
    /// </summary>
    /// <returns>Awaitable task</returns>
    private async Task CallToJS() => await JS.InvokeVoidAsync("sayHi", DotNetObjectReference.Create(this));

    /// <summary>
    /// This method is called from javascript
    /// </summary>
    /// <param name="name">some string parameter coming from javascript</param>
    /// <returns>Returns string</returns>
    [JSInvokable] 
    public async Task<string> CalledFromJS(string name)
    {
        //  Here you can call your class library
        return $"Hi {name}";
    }
}

And this is the JavaScript code calling .NET method

function sayHi(dotNetHelper) {
    var promise = dotNetHelper.invokeMethodAsync('CalledFromJS', "Surinder");

    promise.then(function (result) {
        console.log(result);
    });    
}
2
  • 1
    IJSRuntime requires the Blazor framework - something the asker does not want. Commented Feb 5, 2022 at 19:53
  • Blazor has a clear cut system to call JavaScript functions from .NET code and call .NET functions form JavaScript. I am sorry to say that some times development experience from JavaScript libraries try to implement things the way developers are used to or feel comfortable with. I would say its as important to unlearn somethings as its important to learn new things. So try to understand the intention behind creation of Blazor framework and reap the benefits of it. Its my personal opinion, no intention to hurt anyone. Commented Feb 6, 2022 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.