如何使用Mono WebAssembly在浏览器中运行简单的.NET方法? [英] How do I use Mono WebAssembly to run a simple .NET method in browser?
问题描述
假设我在服务器上有一个.NET dll文件,该文件具有以下简单类:
Let's say I have a .NET dll file on the server, that has this simple class:
public static class C {
public static int Add(int a, int b) => a + b;
}
我想使用Mono的WebAssembly支持在浏览器中调用C.Add
.
(假设我可以将dll下载到浏览器中,例如使用fetch
)
I want to invoke C.Add
in browser using Mono's WebAssembly support.
(assume that I can download the dll into browser, e.g. with fetch
)
问题:
- Mono需要什么.js/.wasm文件,我从哪里得到这些文件?
- 一旦所有内容加载完毕,我该如何从JS中调用
C.Add
?
我检查了npm,但在那里没有找到Mono WASM.
I checked npm but I haven't found Mono WASM there.
注意:我已经有一个dll,所以我对WASM IL解释器感兴趣,而不对WASM AOT构建感兴趣.
Note: I already have a dll, so I'm interested in WASM IL interpreter and not WASM AOT build.
推荐答案
这就是我发现的东西.
- 此处描述了步骤:文档/入门/获取-wasm-sdk.md
- 简短摘要:您必须从Jenkins下载并解压缩版本
- The steps are described here: docs/getting-started/obtain-wasm-sdk.md
- Short summary: you have to download and unpack a build from Jenkins
我们将打开的文件夹称为WASM-SDK
.
Let's call the unpacked folder WASM-SDK
.
注意:如果您按照Mono文档中的说明运行packager.exe
,则可以跳过以下步骤,但是我想在此处描述手动方法,以便更好地理解.
Note: you can skip following steps if you run packager.exe
as described in Mono docs, but I want to describe the manual approach here for better understanding.
在站点根目录下放置以下dll(在managed
文件夹下说):
Put the following dlls under your site root (lets say under managed
folder):
- 包含
class C
的主dll,我们称其为app.dll
- BCL依赖性,在这种情况下,您只需要:
- Main dll that contains
class C
, let's call itapp.dll
- BCL dependencies, in this case you only need:
-
WASM-SDK\wasm-bcl\wasm\mscorlib.dll
-
WASM-SDK\wasm-bcl\wasm\Facades\netstandard.dll
-
WASM-SDK\framework\WebAssembly.Bindings.dll
WASM-SDK\wasm-bcl\wasm\mscorlib.dll
WASM-SDK\wasm-bcl\wasm\Facades\netstandard.dll
WASM-SDK\framework\WebAssembly.Bindings.dll
- 从站点根目录下的
WASM-SDK\release
复制mono.js
和mono.wasm
- 注册您的
Module
并导入mono.js
:
- Copy
mono.js
andmono.wasm
fromWASM-SDK\release
under your site root - Register your
Module
and importmono.js
:
<script>
window.Module = {};
window.Module.onRuntimeInitialized = () => {
const config = {
vfsPrefix: "managed",
deployPrefix: "managed",
enableDebugging: 0
};
const assemblies = [
'app.dll',
'mscorlib.dll',
'WebAssembly.Bindings.dll',
'netstandard.dll'
];
MONO.mono_load_runtime_and_bcl(
config.vfsPrefix,
config.deployPrefix,
config.enableDebugging,
assemblies,
() => {
Module.mono_bindings_init("[WebAssembly.Bindings]WebAssembly.Runtime");
const add = Module.mono_bind_static_method("[app] C:Add");
// ⬇️ This is what calls C.Add():
console.log('C.Add:', add(1, 2));
}
)
};
<script>
<script async src="mono.js"></script>
- 如果使用IIS,请确保
.wasm
扩展名存在application/wasm
mime类型寄存器.
- If using IIS, make sure that there is a
application/wasm
mime type register for the.wasm
extension.
全部完成
现在,一旦打开HTML,您应该会在浏览器控制台中看到C.Add: 3
登录.
这篇关于如何使用Mono WebAssembly在浏览器中运行简单的.NET方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!