webassembly c#如何与JavaScript交互

   2024-09-30 7870
核心提示:WebAssembly 是一种在浏览器中运行的二进制代码格式,它可以让你在浏览器中运行 C# 代码。要实现 WebAssembly 与 JavaScript 之

WebAssembly 是一种在浏览器中运行的二进制代码格式,它可以让你在浏览器中运行 C# 代码。要实现 WebAssembly 与 JavaScript 之间的交互,你需要使用 JavaScript 调用 WebAssembly 函数,或者在 WebAssembly 中调用 JavaScript 函数。

以下是一个简单的示例,展示了如何在 C# 中创建一个 WebAssembly 模块,并在 JavaScript 中调用它:

首先,创建一个 C# 项目,并安装 Microsoft.NET.Sdk.Web SDK。在项目文件中添加以下内容:
 <PropertyGroup>   <TargetFramework>net6.0</TargetFramework>   <OutputType>Exe</OutputType>    <WasmBuildNative>true</WasmBuildNative>  </PropertyGroup>  <ItemGroup>   <PackageReference Include="Microsoft.NET.Runtime.WebAssembly" Version="6.0.0-preview.7.21369.14" />  </ItemGroup></Project>
在项目中创建一个 C# 类,并添加一个简单的方法,例如:
public class MyInteropClass{    public static int Add(int a, int b)    {        return a + b;    }}
在 Program.cs 文件中,将 C# 方法导出为 JavaScript 函数:
using System;using Microsoft.JSInterop;public class Program{    public static void Main()    {        var runtime = new WebAssemblyRuntime();        runtime.InvokeUnmarshalled<string, object>("initialize", "MyInteropClass");    }    [JSInvokable]    public static int Add(int a, int b)    {        return MyInteropClass.Add(a, b);    }}

编译项目,生成 WebAssembly 文件。

在 HTML 文件中,引入 WebAssembly 文件,并调用 C# 方法:

<!DOCTYPE html><html><head>    <meta charset="utf-8" />   <title>WebAssembly Interop Example</title>   <script src="https://cdnjs.cloudflare.com/ajax/libs/mono/6.12.0/mono.js"></script>   <script>        function initialize(className) {            Module.mono_bindings_init("[WebAssembly.Browser.Sample] " + className);        }        function callAdd() {            const a = parseInt(document.getElementById("inputA").value);            const b = parseInt(document.getElementById("inputB").value);            const result = Module.mono_bind_static_method("[WebAssembly.Browser.Sample] MyInteropClass:Add", a, b);            document.getElementById("result").innerText = "Result: " + result;        }    </script></head><body>    <h1>WebAssembly Interop Example</h1>   <input type="number" id="inputA" placeholder="Enter a number" />   <input type="number" id="inputB" placeholder="Enter another number" />   <button onclick="callAdd()">Add</button>    <p id="result"></p>   <script src="https://mykuaidi.com/static/image/lazy.gif" class="lazy" original="https://www.mykuaidi.com/static/image/nopic320.png">

现在,当你在浏览器中打开 HTML 文件时,你可以输入两个数字,然后点击 “Add” 按钮,调用 C# 方法计算结果,并显示在页面上。这就是如何在 WebAssembly 和 JavaScript 之间进行交互的基本示例。

 
举报打赏
 
更多>同类物流大全