👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Using C/C++ Native Dependencies in Blazor WASM

Using C/C++ Native Dependencies in Blazor WASM

Authors - Abdul Rahman (Content Writer), Regina Sharon (Graphic Designer)

Blazor

31 Articles

Improve

Table of Contents

  1. What we gonna do?
  2. Why we gonna do?
  3. How we gonna do?
  4. Summary

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,

  1. Create a new standalone Blazor WebAssembly project.
  2. Add a Test.c file to the project.

    Code Sample - Simple C Test file

  3. Add a NativeFileReference for Test.c in the app's project file.

    Code Sample - NativeFileReference for Test.c

  4. 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#

  5. 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.
Demo Space

Summary

In this article, we learnt about why to reuse other libraries in blazor and how to implement it with a simple example as a native dependency. This helps us to unlock huge possibilities to resue well tested libraries written in other languages in Blazor WebAssembly without need of javascript.
👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • Blazor
  • C
  • C++
  • Native Dependecies