WebAssembly简介及体验

WebAssembly

官方简介
WebAssembly/wasm WebAssembly 或者 wasm 是一个可移植、体积小、加载快并且兼容 Web 的全新格式.
WebAssembly 在 web 中被设计成无版本、特性可测试、向后兼容的。WebAssembly 可以被 JavaScript 调用,进入 JavaScript 上下文,也可以像 Web API 一样调用浏览器的功能。当然,WebAssembly 不仅可以运行在浏览器上,也可以运行在非web环境下。
WebAssembly 有一套完整的语义,实际上 wasm 是体积小且加载快的二进制格式, 其目标就是充分发挥硬件能力以达到原生执行效率.
可以让ffmpeg运行在浏览器环境,unity web也是使用webassembly网页Demo

实验

进入docker编译环境

docker镜像
docker pull abdulachik/ffmpeg.js:latest
docker run -it -p 8080:8080 -v /Users/workspace/Downloads/ffmpeg_wasm:/tmp --privileged=true abdulachik/ffmpeg.js:latest /bin/bash

代码

cd /tmp
touch hello.c
hello.c

#include <stdio.h>
int main(int argc, char ** argv) {
printf("Hello, world!\n");
//注意这里不用return
}

编译测试

emcc ./hello.c -s WASM=1 -o hello.html
我们可以使用 emrun 命令来创建一个 http 协议的 web server 来展示我们编译后的文件。
emrun --no_browser --port 8080 .
浏览器打开http://127.0.0.1:8080/hello.html

编译默认会生成一个2500多行的JavaScript文件hello.js和一个可反编译成文本wat格式的近1万行代码的hello.wasm文件,
hello.js是一坨胶水,用来在不同条件下为wasm搭建一个执行环境.

报错处理

hello.cpp

#include <iostream>
int main(void){
    std::cout<<"hello wasm";
}

编译运行,浏览器控制台报错如下

stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc.

编译出的wasm默认情况下不会退出运行时,这是web情况下期待的方式,主程序main虽然运行结束了,但模块没有退出,静态变量可以保持在内存中,不释放。同时标准 I/O 缓冲区没有被flush,也就没有看到 Hello world.
编译命令改为:
emcc ./hello.cpp -s WASM=1 -s EXIT_RUNTIME=1 -o hello.html

参考文献:

  1. [emscripten 安装与使用, 让C语言出现在前端](https://segmentfault.com/a/1190000038456358?sort=newest/)
  2. WebAssembly中国
posted @ 2022-08-14 23:10  qsBye  阅读(349)  评论(0编辑  收藏  举报