- WebAssembly 教程
- WebAssembly - 主页
- WebAssembly - 概述
- WebAssembly - 简介
- WebAssembly - WASM
- WebAssembly - 安装
- WebAssembly - 编译到 WASM 的工具
- WebAssembly - 程序结构
- WebAssembly - JavaScript
- WebAssembly - JavaScript API
- WebAssembly - 在 Firefox 中调试 WASM
- WebAssembly - “你好,世界”
- WebAssembly - 模块
- WebAssembly - 验证
- WebAssembly - 文本格式
- WebAssembly - 将 WAT 转换为 WASM
- WebAssembly - 动态链接
- WebAssembly - 安全性
- WebAssembly - 使用 C
- WebAssembly - 使用 C++
- WebAssembly - 使用 Rust
- WebAssembly - 使用 Go
- WebAssembly - 使用 Nodejs
- WebAssembly - 示例
- WebAssembly 实用资源
- WebAssembly - 快速指南
- WebAssembly - 实用资源
- WebAssembly - 讨论
WebAssembly - 使用 C++
在本章中,我们将把一个简单的 C++ 程序编译为 javascript,并在浏览器中执行该程序。
示例
C++ 程序 - 反转给定的数字。
#include <iostream>
int reversenumber(int n) {
int reverse=0, rem;
while(n!=0) {
rem=n%10; reverse=reverse*10+rem; n/=10;
}
return reverse;
}
我们在 wa/ 文件夹中安装了 emsdk。在同一文件夹中,创建另一个文件夹 cprog/ 并将上述代码保存为 reverse.cpp。
我们已经在上一章中安装了 emsdk。在这里,我们将使用 emsdk 来编译上面的 c 代码。
如下所示,在命令提示符中编译 test.c −
emcc reverse.cpp -s STANDALONE_WASM –o reverse.wasm
emcc 命令负责编译代码并给你 .wasm 代码。
示例 − reversenumber.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WebAssembly Reverse Number</title>
<style>
div {
font-size : 30px; text-align : center; color:orange;
}
</style>
</head>
<body>
<div id="textcontent"></div>
<script>
let reverse;
fetch("reverse.wasm")
.then(bytes => bytes.arrayBuffer())
.then(mod => WebAssembly.compile(mod))
.then(module => {return new WebAssembly.Instance(module) })
.then(instance => {
console.log(instance);
reverse = instance.exports._Z13reversenumberi(1439898);
console.log("The reverse of 1439898 = " +reverse);
document.getElementById("textcontent")
.innerHTML = "The reverse of 1439898 = " +reverse;
});
</script>
</body>
</html>
输出
输出如下 −
广告