Skip to content

Instantly share code, notes, and snippets.

@am11
Last active June 4, 2023 23:24
Show Gist options
  • Save am11/159ad22a8f5131f3d8811f1c8b34d75b to your computer and use it in GitHub Desktop.
Save am11/159ad22a8f5131f3d8811f1c8b34d75b to your computer and use it in GitHub Desktop.
.NET <-> Deno Interop

Following workloads are required on the system:

$ dotnet workload install wasm-tools wasm-experimental # may require sudo

Build & Run:

$ dotnet build
$ deno run --allow-read bin/Debug/net7.0/browser-wasm/AppBundle/myApp.js

Sample output:

MONO_WASM: WebAssembly resource does not have the expected content type "application/wasm", so falling back to slower ArrayBuffer instantiation.
mono_wasm_runtime_ready fe00e07a-5519-4dfe-b35a-f867dbaf2e28
Hello from Deno!
            deno version: 1.29.1
            typescript version: 4.9.4
            v8 version: 10.9.194.5
Hello from C# Console!
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
<WasmMainJSPath>myApp.js</WasmMainJSPath>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>
import { dotnet } from './dotnet.js'
const { setModuleImports, getAssemblyExports, getConfig } = await dotnet
.withDiagnosticTracing(false)
.create();
setModuleImports('MyDenoModule', {
DenoVersions: () => globalThis.Deno.version
});
const config = getConfig();
const exports = await getAssemblyExports(config.mainAssemblyName);
const text = exports.Fiddle.Greeting();
console.log(text);
await dotnet.run();
using System;
using System.Runtime.Versioning;
using System.Runtime.InteropServices.JavaScript;
[assembly:SupportedOSPlatform("browser")]
public partial class Fiddle
{
private static void Main () => Console.WriteLine("Hello from C# Console!");
[JSExport]
private static string Greeting()
{
using JSObject versions = GetDenoVersions();
string text = $@"Hello from Deno!
deno version: {versions.GetPropertyAsString("deno")}
typescript version: {versions.GetPropertyAsString("typescript")}
v8 version: {versions.GetPropertyAsString("v8")}";
return text;
}
[JSImport("DenoVersions", "MyDenoModule")]
private static partial JSObject GetDenoVersions();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment