首頁 >web前端 >js教程 >WebAssembly (WASM) 簡介

WebAssembly (WASM) 簡介

Barbara Streisand
Barbara Streisand原創
2025-01-11 07:26:421006瀏覽

Introduction to WebAssembly (WASM)

WebAssembly (WASM) 是一種基於堆疊的虛擬機器的二進位指令格式,設計為高效能應用程式的便攜式目標。在本文中,我們將探討如何將簡單的 C 程式編譯為 WebAssembly,將其載入到 Web 瀏覽器中,並使用 JavaScript 與其互動。我們還將探索一些在開發容器環境之外使用 WASM 的有用工具和命令。

設定開發環境

為您的 WebAssembly 專案建立必要的資料夾結構和檔案。

  1. 建立專案資料夾: 首先為您的專案建立一個新目錄。在此資料夾中,您將新增必要的檔案和配置。
   mkdir wasm-web-example
   cd wasm-web-example
  1. 設定開發容器: 在 wasm-web-example 目錄中,建立 .devcontainer 資料夾來儲存 dev 容器設定檔。這些檔案將設定一個安裝了 Emscripten 的容器,用於將 C 程式碼編譯成 WebAssembly。

在 .devcontainer 資料夾中,建立以下檔案:

  • devcontainer.json

    此檔案將 VSCode 配置為使用具有必要擴充功能和環境設定的 Docker 容器。

     {
       "name": "Emscripten DevContainer",
       "build": {
         "dockerfile": "Dockerfile"
       },
       "customizations": {
         "vscode": {
           "settings": {
             "terminal.integrated.shell.linux": "/bin/bash",
             "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools",
             "C_Cpp.default.intelliSenseMode": "gcc-x64"
           },
           "extensions": [
             "ms-vscode.cpptools",
             "ms-vscode.cmake-tools"
           ]
         }
       },
       "postCreateCommand": "emcc --version"
     }
    
  • Dockerfile

    Dockerfile 將設定 Emscripten 環境。這是該文件的內容:

     # Use the official Emscripten image
     FROM emscripten/emsdk:3.1.74
    
     # Set the working directory
     WORKDIR /workspace
    
     # Copy the source code into the container
     COPY . .
    
     # Install any additional packages if necessary (optional)
     # Ensure to clean up cache to minimize image size
     RUN apt-get update && \
         apt-get install -y build-essential && \
         apt-get clean && \
         rm -rf /var/lib/apt/lists/*
    
  1. 建立 VSCode 設定: 在專案的根目錄中,建立一個包含以下檔案的 .vscode 資料夾:
  • c_cpp_properties.json

    此檔案配置 C IntelliSense 並包含專案的路徑。

     {
       "configurations": [
         {
           "name": "Linux",
           "includePath": [
             "${workspaceFolder}/**",
             "/emsdk/upstream/emscripten/system/include"
           ],
           "defines": [],
           "compilerPath": "/usr/bin/gcc",
           "cStandard": "c17",
           "cppStandard": "gnu++17",
           "configurationProvider": "ms-vscode.cmake-tools"
         }
       ],
       "version": 4
     }
    
  • settings.json

    此檔案包含語言關聯的特定 VSCode 設定。

     {
       "files.associations": {
         "emscripten.h": "c"
       },
       "[javascript]": {
         "editor.defaultFormatter": "vscode.typescript-language-features"
       },
       "[typescript]": {
         "editor.defaultFormatter": "vscode.typescript-language-features"
       },
       "[jsonc]": {
         "editor.defaultFormatter": "vscode.json-language-features"
       },
       "[json]": {
         "editor.defaultFormatter": "vscode.json-language-features"
       },
       "[html]": {
         "editor.defaultFormatter": "vscode.html-language-features"
       }
     }
    
  1. 建立 C、JavaScript 和 HTML 檔案: 現在,為您的專案建立以下文件:
  • test.c

    這個 C 檔案包含將被編譯為 WebAssembly 的簡單函數。

     // test.c
     int add(int lhs, int rhs) {
         return lhs + rhs;
     }
    
  • test.html

    此 HTML 檔案將使用 JavaScript 載入 WebAssembly 模組。

     <!DOCTYPE html>
     <html lang="en">
       <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>WebAssembly Example</title>
       </head>
       <body>
         <h1>WebAssembly Example</h1>
         <div>
    
    </li>
    <li>
    <p><strong>test.js</strong><br><br>
     This JavaScript file will fetch the WebAssembly module and call the exported function.<br>
    </p>
    <pre class="brush:php;toolbar:false"> // test.js
     const wasmFile = 'test.wasm';
    
     fetch(wasmFile)
       .then(response => response.arrayBuffer())
       .then(bytes => WebAssembly.instantiate(bytes))
       .then(({ instance }) => {
         const result = instance.exports.add(5, 3); // Call the WebAssembly function
         document.getElementById('output').textContent = `Result from WebAssembly: ${result}`;
       })
       .catch(error => console.error('Error loading WebAssembly module:', error));
    

現在您已經設定了所有必要的檔案和配置,您可以繼續編譯 WebAssembly 並與 WebAssembly 互動。

使用 Emscripten 將 C 程式碼編譯為 WebAssembly

  1. 基礎 C 程式:

    檔案 test.c 包含一個簡單的函數 add,用於將兩個整數相加。我們將使用 Emscripten 將此 C 函數編譯為 WebAssembly。

  2. Emscripten 指令:

    在 dev 容器內,開啟終端機(在 VSCode 中使用 cmd j)並執行以下 Emscripten 指令將 C 程式碼編譯為 WebAssembly:

   mkdir wasm-web-example
   cd wasm-web-example

此命令將產生 test.wasm(WebAssembly 二進位檔案),並確保匯出 add 函數以在 JavaScript 中使用。

在瀏覽器中載入 WebAssembly 並與之互動

  1. HTML 設定:

    檔案 test.html 包含一個簡單的 HTML 頁面,該頁面使用 JavaScript 載入 WebAssembly 二進位。

  2. JavaScript 設定:

    JavaScript 檔案 test.js 載入 test.wasm 檔案並呼叫匯出的 add 函數:

在 macOS 上使用外部工具

在開發容器之外,您可以執行幾個有用的命令來在 Mac 上使用 WebAssembly。

  1. 安裝wabt: wabt(WebAssembly 二進位工具包)提供了用於使用 WebAssembly 的實用程序,包括將 .wasm 檔案轉換為人類可讀的 WAT(WebAssembly 文字)格式。透過 Homebrew 安裝:
 {
   "name": "Emscripten DevContainer",
   "build": {
     "dockerfile": "Dockerfile"
   },
   "customizations": {
     "vscode": {
       "settings": {
         "terminal.integrated.shell.linux": "/bin/bash",
         "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools",
         "C_Cpp.default.intelliSenseMode": "gcc-x64"
       },
       "extensions": [
         "ms-vscode.cpptools",
         "ms-vscode.cmake-tools"
       ]
     }
   },
   "postCreateCommand": "emcc --version"
 }
  1. 將 WASM 轉換為 WAT: 安裝 wabt 後,您可以使用 wasm2wat 工具將 WebAssembly 二進位檔案 (test.wasm) 轉換為 WAT 格式:
 # Use the official Emscripten image
 FROM emscripten/emsdk:3.1.74

 # Set the working directory
 WORKDIR /workspace

 # Copy the source code into the container
 COPY . .

 # Install any additional packages if necessary (optional)
 # Ensure to clean up cache to minimize image size
 RUN apt-get update && \
     apt-get install -y build-essential && \
     apt-get clean && \
     rm -rf /var/lib/apt/lists/*
  1. 提供 HTML 頁面: 若要查看與 WebAssembly 模組互動的 HTML 頁面,可以使用 Python 的簡單 HTTP 伺服器:
 {
   "configurations": [
     {
       "name": "Linux",
       "includePath": [
         "${workspaceFolder}/**",
         "/emsdk/upstream/emscripten/system/include"
       ],
       "defines": [],
       "compilerPath": "/usr/bin/gcc",
       "cStandard": "c17",
       "cppStandard": "gnu++17",
       "configurationProvider": "ms-vscode.cmake-tools"
     }
   ],
   "version": 4
 }

結論

透過執行以下步驟,您可以設定一個開發環境,將 C 程式碼編譯為 WebAssembly,使用 JavaScript 與其交互,並轉換產生的二進位檔案以供檢查。使用 wabt 和 Python 的 HTTP 伺服器等外部工具簡化了 macOS 系統上的 WebAssembly 模組的管理和探索。

以上是WebAssembly (WASM) 簡介的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn