WebAssembly (WASM) 是一種基於堆疊的虛擬機器的二進位指令格式,設計為高效能應用程式的便攜式目標。在本文中,我們將探討如何將簡單的 C 程式編譯為 WebAssembly,將其載入到 Web 瀏覽器中,並使用 JavaScript 與其互動。我們還將探索一些在開發容器環境之外使用 WASM 的有用工具和命令。
為您的 WebAssembly 專案建立必要的資料夾結構和檔案。
mkdir wasm-web-example cd wasm-web-example
在 .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/*
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" } }
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 互動。
基礎 C 程式:
檔案 test.c 包含一個簡單的函數 add,用於將兩個整數相加。我們將使用 Emscripten 將此 C 函數編譯為 WebAssembly。
Emscripten 指令:
在 dev 容器內,開啟終端機(在 VSCode 中使用 cmd j)並執行以下 Emscripten 指令將 C 程式碼編譯為 WebAssembly:
mkdir wasm-web-example cd wasm-web-example
此命令將產生 test.wasm(WebAssembly 二進位檔案),並確保匯出 add 函數以在 JavaScript 中使用。
HTML 設定:
檔案 test.html 包含一個簡單的 HTML 頁面,該頁面使用 JavaScript 載入 WebAssembly 二進位。
JavaScript 設定:
JavaScript 檔案 test.js 載入 test.wasm 檔案並呼叫匯出的 add 函數:
在開發容器之外,您可以執行幾個有用的命令來在 Mac 上使用 WebAssembly。
{ "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" }
# 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/*
{ "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中文網其他相關文章!