Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ be called from C# compiled to wasm?

Does anyone know if it's currently possible to call C++ from C# compiled to wasm (or an Uno Platform app to be more precise)?

I'm fairly new to WebAssembly but I managed to compile a C++ function to wasm and call it from JavaScript. I also got the quick start project from Uno (which allows you to compile UWP apps written in C#/XAML to wasm and run them in the browser) running.

I write both C# and C++ on a daily basis, but what I can't figure out is the "interopping between 2 languages" + WebAssembly combo. I assume I need to compile the code in both languages to 2 separate wasm files and then somehow link them together or load the C++ one at runtime. Is what I want to do even possible at all today?

EDIT: To be clear: the idea is that all code is eventually compiled to wasm.

like image 759
Stan Wijckmans Avatar asked Jun 05 '19 19:06

Stan Wijckmans


People also ask

Can I call C from rust?

Rust can link to/call C functions via its FFI, but not C++ functions.

Can C and C++ be mixed?

C++ is a superset of C. Therefore, any valid C program is a valid C++ program, and there is no such thing as "mixing" C into C++. @Jonathan: int main() { int class = 2; } (valid C, not valid C++) C++ is not a superset of C; C and C++ share a common subset.

Can C libraries be used in C++?

Yes - C++ can use C libraries.

Can we call C++ library function directly from C library?

Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.


1 Answers

P/Invoke is supported since last month by the mono-wasm runtime, using two modes:

  • Dynamic linking of an arbitrary WebAssembly module, when running with the mono interpreter
  • Static linking of LLVM bitcode files generated by prior emscripten invocations, when running under mono's AOT

The latter is being worked on at the moment in the Uno.Wasm.Bootstrapper in this PR.

It has the exact same behavior another .NET runtime may have, which means that C++ cannot be access directly, and you'll have to expose a C API to be able to use it.

There are some caveats with the use of C++, where the runtime needs to be forcibly included in the mono runtime's binaries, making it larger. This may change soon, since emscripten is moving to a full LLVM backend.

Some documentation is for the Uno.Wasm.Bootstrapper is available here.

like image 62
Jérôme Laban Avatar answered Sep 27 '22 01:09

Jérôme Laban