Using C/C++ Native Dependencies in Blazor WASM
Blazor
31 Articles
Table of Contents
What we gonna do?
In this article let's learn how to use libraries written in other languages like C/C++ in Blazor WebAssembly directly in browser. Thanks to the fact that we have blazor running on WebAssembly. we also get access to other things. All these are made possible with WebAssembly.
Why we gonna do?
The main reason to use libraries written in other languages is that it gives us access to powerful and highly optimized code that is already battle tested and refined without reinventing the wheel. These libraries performs the task at near Native speeds and WebAssembly gives us the ability to run these code directly in browser with similar performance like how we run in desktop machine without need of javascript.
For example, we can take graphic libraries already written in other languages and reuse them without reinventing the wheel in dotnet. Skia library written in C++ is a good example. It is a powerful 2D graphics library that is already used in android, chrome, flutter to render highly quality graphics.
How we gonna do?
Please note that as of writing this, Native Dependencies are not supported with Lazy Loaded Assemblies. As a workaround, you need refer the Native Dependencies from startup project instead of Lazy Loaded RCL.All you need to do is,
- Create a new standalone Blazor WebAssembly project.
Add a Test.c file to the project.
Code Sample - Simple C Test file
Add a NativeFileReference for Test.c in the app's project file.
Code Sample - NativeFileReference for Test.c
In a Razor component, add a DllImportAttribute for the fact function in the generated Test library and call the fact method from .NET code in the component.
Code Sample - Calling C function from C#
- When you build the app with the .NET WebAssembly build tools installed, the native C code is compiled and linked into the .NET WebAssembly runtime (dotnet.wasm). After the app is built, run the app to see the rendered factorial number.