关于webassembly:WebAssembly-与-net

7次阅读

共计 4655 个字符,预计需要花费 12 分钟才能阅读完成。

.Net 目前反对 WebAssembly。

基本上目前有两种应用场景:

  • 浏览器端 — 通过 Blazor WebAssembly,给了咱们应用.net 编写前端利用的能力,并且能够享受.net 自身具备的诸如类型平安和优雅的语法。
  • 服务端 — .net 程序中应用其余语言编写的 wasm 模块。

上面咱们通过两个 demo 别离演示一下这两种场景的应用姿态。

浏览器端

不得不提微软大法好。.Net 在浏览器端对 wasm 的反对十分优良,次要是推出了 Blazor WebAssembly 这一神器。

在讲 Blazor WebAssembly 之前,咱们先介绍一下什么是 Blazor?

Blazor 是一个凋谢源代码和跨平台的 Web UI 框架,用于应用.NET 和 C#而不是 JavaScript 来构建单页应用程序。Blazor 基于弱小而灵便的组件模型,用于构建丰盛的交互式 Web UI。您能够联合应用.NET 代码和 Razor 语法来实现 Blazor UI 组件:HTML 和 C#的完满交融。Blazor 组件能够无缝解决 UI 事件,绑定到用户输出并无效地出现 UI 更新。

而后能够以不同的形式托管 Blazor 组件,以创立您的 Web 应用程序。第一种受反对的形式称为 Blazor 服务器。在 Blazor Server 应用程序中,组件应用.NET Core 在服务器上运行。所有 UI 交互和更新都应用与浏览器的实时 WebSocket 连贯进行解决。Blazor Server 应用程序加载迅速且易于实现。.NET Core 3.1 LTS 提供了对 Blazor 服务器的反对。

Blazor WebAssembly 当初是托管 Blazor 组件的第二种受反对的形式:在客户端应用基于 WebAssembly 的.NET 运行时。

Blazor WebAssembly 可与所有古代的 Web 浏览器(台式机和挪动设施)一起应用。与 JavaScript 类似,Blazor WebAssembly 利用可从浏览器的平安沙箱中平安地在用户设施上运行。这些应用程序能够作为齐全独立的动态站点进行部署,而基本没有任何.NET 服务器组件,或者能够与 http://ASP.NET Core 配对应用,从而能够通过.NET 进行全栈 Web 开发,从而能够轻松地与客户端和服务器共享代码。

上面咱们简略通过一个示例让大家理解一下。

1:咱们能够间接通过命令创立一个我的项目(由此可见微软对于 Blazor WebAssembly 的器重和反对力度):

$ mkdir wasmblazor
$ cd wasmblazor
$ dotnet new blazorwasm 
The template "Blazor WebAssembly App" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on /Users/iyacontrol/dotnet/wasmblazor/wasmblazor.csproj...
  Determining projects to restore...
/usr/local/share/dotnet/sdk/3.1.402/NuGet.targets(128,5): error : Unable to load the service index for source https://api.nuget.org/v3/index.json. [/Users/iyacontrol/dotnet/wasmblazor/wasmblazor.csproj]
/usr/local/share/dotnet/sdk/3.1.402/NuGet.targets(128,5): error :   nodename nor servname provided, or not known [/Users/iyacontrol/dotnet/wasmblazor/wasmblazor.csproj]

Restore failed.
Post action failed.
Description: Restore NuGet packages required by this project.
Manual instructions: Run 'dotnet restore'

2:运行

dotnet run
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:8001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:8000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /Users/iyacontrol/dotnet/wasmblazor

拜访 http://localhost:8000,呈现如下页面:

整个我的项目,没有用到任何的 js,全副由 c#代码实现。c# 代码被编译成 wasm,在浏览器中执行。能够说,微软的 Blazor 真是恰到好处的将 wasm 使用起来。

服务器端

.net 可能应用 WebAssembly 作为公共字节码,并应用 WASI 作为公共接口,从而在 Web 浏览器以外的任何中央运行 WebAssembly 代码

在.NET 中运行 WASM 代码的以后最简略,最间接的办法之一是应用 Wasmtime 的 wasmtime-dotnet.NET 嵌入运行时。

1: 筹备 wasm 模块,供后续的 dotnet 程序应用。

有许多编译器工具能够将 C 或 C ++ 代码编译为 WebAssembly。Emscripten 是最罕用的一种。本次咱们应用 Emscripten 将 C /C ++ 代码编译为 WebAssembly。

创立一个 fibonacci.c 文件,内容如下:

#include <emscripten.h>

EMSCRIPTEN_KEEPALIVE
int fib(int n) {if(n <= 0){return 0;}

  int i, t, a = 0, b = 1;

  for (i = 1; i < n; i++) {
    t = a + b;
    a = b;
    b = t;
  }
  
  return b;
} 

顾名思义,大家曾经晓得实现了一个计算斐波那契数列的性能。

须要 EMSCRIPTEN_KEEPALIVE 宏标记函数,该宏会确保该函数不会被内联,并将被导出以供内部应用。

接下来咱们编译 c 代码为 wasm 模块。为了不便,间接应用 docker 镜像作为编译环境,省去了咱们配置环境的懊恼。

docker run 
  --rm 
  -v `pwd`:`pwd` 
  -w `pwd` 
  -u $(id -u):$(id -g) 
  emscripten/emsdk 
  emcc native/fibonacci.c -o wasm/fibonacci.wasm --no-entry

在 wasm 文件夹下生成了 fibonacci.wasm。

2:创立 dotnet 工程。

$ mkdir wasmintro
$ cd wasmintro
$ dotnet new console

Welcome to .NET Core 3.1!
---------------------
SDK Version: 3.1.402

Telemetry
---------
The .NET Core tools collect usage data in order to help us improve your experience. The data is anonymous. It is collected by Microsoft and shared with the community. You can opt-out of telemetry by setting the DOTNET_CLI_TELEMETRY_OPTOUT environment variable to '1' or 'true' using your favorite shell.

Read more about .NET Core CLI Tools telemetry: https://aka.ms/dotnet-cli-telemetry

----------------
Explore documentation: https://aka.ms/dotnet-docs
Report issues and find source on GitHub: https://github.com/dotnet/core
Find out what's new: https://aka.ms/dotnet-whats-new
Learn about the installed HTTPS developer cert: https://aka.ms/aspnet-core-https
Use 'dotnet --help' to see available commands or visit: https://aka.ms/dotnet-cli-docs
Write your first app: https://aka.ms/first-net-core-app
--------------------------------------------------------------------------------------
Getting ready...
The template "Console Application" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on /Users/iyacontrol/dotnet/wasmintro/wasmintro.csproj...
  Determining projects to restore...
  Restored /Users/iyacontrol/dotnet/wasmintro/wasmintro.csproj (in 155 ms).

Restore succeeded.

目前 dotnet core 最新版本为 3.1。

3:咱们能够通过增加 Nuget 包将其增加到咱们的我的项目中:dotnet add package --version 0.19.0-preview1 wasmtime(撰写本文时的预览版)

4:编写主程序Program.cs。具体如下:

using System;
using Wasmtime;

namespace wasmintro
{
    class Program
    {static void Main(string[] args)
        {using var engine = new Engine();

            using var module = Module.FromFile(engine,"wasm/fibonacci.wasm");

            using var host = new Host(engine);
            using dynamic instance = host.Instantiate(module);

            var result = instance.fib(7);
            Console.WriteLine(result);
            
        }
    }
} 

5: 运行程序

dotnet run
13

咱们的程序曾经完满运行了。

总结

本文介绍了 WebAssembly 与 .net 两种应用姿态。尤其是在浏览器端,微软通过 Blazor WebAssembly,给与了.net 开发者全栈的能力。

正文完
 0