WebAssembly (WASM) 是一种基于堆栈的虚拟机的二进制指令格式,设计为高性能应用程序的便携式目标。在本文中,我们将探讨如何将简单的 C 程序编译为 WebAssembly,将其加载到 Web 浏览器中,并使用 JavaScript 与其交互。我们还将探索一些在开发容器环境之外使用 WASM 的有用工具和命令。
设置开发环境
为您的 WebAssembly 项目创建必要的文件夹结构和文件。
- 创建项目文件夹: 首先为您的项目创建一个新目录。在此文件夹中,您将添加必要的文件和配置。
mkdir wasm-web-example cd wasm-web-example
- 设置开发容器: 在 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/*
- 创建 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" } }
- 创建 C、JavaScript 和 HTML 文件: 现在,为您的项目创建以下文件:
-
test.c
这个 C 文件包含将被编译为 WebAssembly 的简单函数。
// test.c int add(int lhs, int rhs) { return lhs + rhs; }
-
test.html
此 HTML 文件将使用 JavaScript 加载 WebAssembly 模块。
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebAssembly Example</title> <h1 id="WebAssembly-Example">WebAssembly Example</h1> <div> <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));
基础 C 程序:
文件 test.c 包含一个简单的函数 add,用于将两个整数相加。我们将使用 Emscripten 将此 C 函数编译为 WebAssembly。Emscripten 命令:
在 dev 容器内,打开终端(在 VSCode 中使用 cmd j)并运行以下 Emscripten 命令将 C 代码编译为 WebAssembly:
现在您已经设置了所有必要的文件和配置,您可以继续编译 WebAssembly 并与 WebAssembly 交互。
使用 Emscripten 将 C 代码编译为 WebAssembly
mkdir wasm-web-example cd wasm-web-example
此命令将生成 test.wasm(WebAssembly 二进制文件),并确保导出 add 函数以在 JavaScript 中使用。
在浏览器中加载 WebAssembly 并与之交互
HTML 设置:
文件 test.html 包含一个简单的 HTML 页面,该页面使用 JavaScript 加载 WebAssembly 二进制文件。JavaScript 设置:
JavaScript 文件 test.js 加载 test.wasm 文件并调用导出的 add 函数:
在 macOS 上使用外部工具
在开发容器之外,您可以运行几个有用的命令来在 Mac 上使用 WebAssembly。
- 安装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" }
- 将 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/*
- 提供 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中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

简单JavaScript函数用于检查日期是否有效。 function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //测试 var

本文探讨如何使用 jQuery 获取和设置 DOM 元素的内边距和外边距值,特别是元素外边距和内边距的具体位置。虽然可以使用 CSS 设置元素的内边距和外边距,但获取准确的值可能会比较棘手。 // 设置 $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); 你可能会认为这段代码很

本文探讨了十个特殊的jQuery选项卡和手风琴。 选项卡和手风琴之间的关键区别在于其内容面板的显示和隐藏方式。让我们深入研究这十个示例。 相关文章:10个jQuery选项卡插件

发现十个杰出的jQuery插件,以提升您的网站的活力和视觉吸引力!这个精选的收藏品提供了不同的功能,从图像动画到交互式画廊。让我们探索这些强大的工具: 相关文章: 1

HTTP-Console是一个节点模块,可为您提供用于执行HTTP命令的命令行接口。不管您是否针对Web服务器,Web Serv

本教程向您展示了如何将自定义的Google搜索API集成到您的博客或网站中,提供了比标准WordPress主题搜索功能更精致的搜索体验。 令人惊讶的是简单!您将能够将搜索限制为Y

当div内容超出容器元素区域时,以下jQuery代码片段可用于添加滚动条。 (无演示,请直接复制到Firebug中) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3汉化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版

记事本++7.3.1
好用且免费的代码编辑器

Dreamweaver CS6
视觉化网页开发工具