10

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.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Stan Wijckmans
  • 396
  • 3
  • 10
  • [This](https://learn.microsoft.com/en-us/cpp/dotnet/how-to-call-native-dlls-from-managed-code-using-pinvoke?view=vs-2019) might be useful. – Orkhan Alikhanov Jun 05 '19 at 19:31
  • @OrkhanAlikhanov I don't think that's going to work. I don't really have a native dll: my C++ should also be wasm and run cross platform in the browser. And even if it would be a native dll then I doubt PInvoking is going to work, it's not the good old CLR afterall. – Stan Wijckmans Jun 05 '19 at 19:44
  • Ok @OrkhanAlikhanov, PInvoke does seem to be the way to go, but needs to be properly set up in the project first. – Stan Wijckmans Jun 06 '19 at 07:04

1 Answers1

8

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.

David Oliver
  • 2,251
  • 12
  • 12
Jérôme Laban
  • 5,224
  • 3
  • 20
  • 17