Summary:

WebAssembly, referred to as WASM, is a new coding method, similar to assembly language, can be close to the native performance to run on the Web, is a portable, small, fast loading and compatible with the New web format, he has several characteristics

  • Fast, efficient, portable – WebAssembly code can run at near-native speed on different platforms by taking advantage of common hardware capabilities.
  • Readable, debuggable – WebAssembly is a low-level language, but it does have a human-readable text format (its standards are about to be finalized) that allows you to write, view, and debug code by hand.
  • Stay Safe – WebAssembly is restricted to running in a secure sandbox execution environment. Like other web code, it follows the browser’s same-origin and authorization policies.
  • Don’t Break the Web – WebAssembly is designed to live in harmony with other web technologies and maintain backward compatibility.

WebAssembly is a low-level assembly like language. It has a compact binary format that allows it to run at near native performance, and it provides a compilation target for languages such as C++ and Rust that have low-level memory models so they can run on the network. WebAssembly is currently supported in most browsers and is being added and maintained.

Implementation principle:

The traditional JavaScript code is run in the virtual machine in the browser, and the use of JavaScript high-level language can solve the vast majority of problems in the usual Web scene. However, when confronted with technologies such as network, 3D, AR, VR and so on, the performance bottleneck of JavaScript is highlighted. And the browser needs to load JavaScript and parse it, which is also very resource-intensive, so WebAssembly’s capabilities come into play.

The new virtual machine will load both JavaScript and WebAssembly, both of which will also use apis to call each other:

Graph TD Browser --> JavaScript Virtual machine --> JavaScript Virtual machine --> WebAssembly

Of course, WebAssembly is not limited to the Web environment, it also supports non-Web environment (such as Node environment), any supporting WebAssembly environment must provide the following support:

  • 8 bit bytes.
  • Memory is addressable by byte dimension.
  • Support for unaligned memory access or known defects due to software emulation.
  • 32 – bit signed integers have two complements, 64 – bit optional.
  • IEEE 754-2008 32 – and 64-bit floating point numbers, with some exceptions.
  • Small endian byte order.
  • Memory regions can be efficiently processed using 32-bit Pointers or indexes.
  • WebAssembly64 supports up to 4GB of additional linear memory using 64-bit Pointers or indexes.
  • Enforce security isolation of WebAssembly modules on the same machine from other modules or processes
  • Provide an execution environment in which a process guarantees the execution of all threads (even if they execute in non-parallel mode)
  • Lock-free atom operators are used to access 8, 16, and 32 bit naturally aligned memory. Also include at least an atomic comparison and swap operator (or equivalent load join/conditional store).
  • WebAssembly64 requires an additional lock-free atom operator to access 64-bit naturally aligned memory.

Emscripten introduction

To execute C/C++ code on the Web, you need a tool to compile the code into a. Wasm (WebAssembly Execution module) file. There are many such tools, and Enscripten is the most mature one at present.

Emscripten takes a piece of C/C++ code and compiles it to:

  • A. Wasm module
  • The JavaScript “glue” code used to load and run the module
  • An HTML document that shows the results of running the code

The working process is as follows:

Here is a sample flow for Mac:

The installation

git clone https://github.com/juj/emsdk.git cd emsdk ./emsdk install latest ./emsdk activate latest source ./emsdk_env.sh Register environment variablesCopy the code

Write test code

mkdir hello
cd hello
touch hello.c
Copy the code

Then open hello. C with an editor and paste the following code:

#include <stdio.h>
int main(int argc, char ** argv) {
    printf("Hello, world!");
}

Copy the code

compile

emcc ./hello.c -s WASM=1 -s EXIT_RUNTIME=1 -o hello.html
Copy the code

Here’s an explanation:

  • WASM=1: WASM files are generated instead of ASM files. The default version is WASM
  • EXIT_RUNTIME=1: Compiled wASM does not exit by default, which is expected on the Web. The main program is finished, but the module does not exit, and static variables can be kept in memory. If the standard I/O buffer is not flushed, add this parameter to end the module to see the I/O output, otherwise you will not see printf output
  • O: Output file format
  • O: Specifies the optimization level. The optimization level can be -O0, -O1, -O2, or -O3-OS. -o0 is not specified, that is, there is no optimization. Generally, -o0 or -o1 is specified during development. In this way, compilation speed is fast and debugging is convenient. It can be -O2 or -O3 for official release, where the code is optimized and executed faster. -Os not only performs fast, but also optimizes the size to generate smaller execution files.

The hello. HTML hello.js and hello.wasm files are generated in the directory.

run

Most browsers cannot load files using the file://, so you need to start a web server, either using node’s live-server or using emcc’s built-in web server

npm install live-server
live-server ./
Copy the code

or

emrun --no_browser --port 8080 .
Copy the code

So when we open the browser, we can see our Hello World:

Analysis of the

At this point, one of the most basic C/C++ code is running in the Web environment. Let’s look at the hello.html hello.js and hello.wasm files in reverse.

  • Hello. Wasm Binary WASM module code
  • Hello.js is a JavaScript file that contains glue code for converting between native C functions and JavaScript/ wASM
  • Hello.html An HTML file used to load, compile, instantiate, and output your WASM code to a browser display

JavaScript interacts with C/C++

Specify your own template HTML file

Create a folder in the current directory to place your OWN HTML template files

mkdir html_template
Copy the code

Then search for a file called shell_minimal. HTML in emSDK and copy it to the html_template folder in the directory you just created

cp ~/emsdk/upstream/emscripten/src/shell_minimal.html html_template
Copy the code

Use –shell-file html_template/shell_minimal. HTML to specify the template file

emcc ./hello.c -s WASM=1 -s EXIT_RUNTIME=1 --shell-file html_template/shell_minimal.html -o hello.html
Copy the code

Restart the Web Server to see it in action

Rewrite the hello. C

#include <stdio.h>
#include <emscripten/emscripten.h>

int main(int argc, char ** argv) {
    printf("Hello World\n");
}

#ifdef __cplusplus
extern "C" {
#endif

int EMSCRIPTEN_KEEPALIVE myFunction(int argc, char ** argv) {
  printf("My function has been called \n");
}

#ifdef __cplusplus
}
#endif
Copy the code

By default, emscripten only generates the main function. If you want to use a specified function, you need to specify EMSCRIPTEN_KEEPALIVE but import emscripten.h

emcc ./hello.c -s WASM=1 -s "EXPORTED_RUNTIME_METHODS=['ccall']" --shell-file html_template/shell_minimal.html -o hello.html
Copy the code

EXPORTED_RUNTIME_METHODS=[‘ccall’]”, and remove -s EXIT_RUNTIME=1, the program cannot exit, it must always be executed.

Add interactive buttons

Open our shell_minimal.html file and add a button:

Then, in<script>and</script>Register the response function inRerun theemccCommand to generate new HTML, restart the Web Server, and the page will appear with a button that you can click to seeMy function has been calledAnd the console can also see the corresponding MSG

The role of WebAssembly

WebAssembly based on its good performance, and can easily enhance web ability, can experience the official to write based on the unity of a demo www.wasm.com.cn/demo/Tanks/ support situation of the current mainstream browsers and node:

Believe that WebAssembly will provide more possibilities for the Web

  • Web support FFmpeg
  • Web support OpenAL
  • Web support OpenCV
  • .

Follow-up article plan

  • WebAssembly -c calls the JavaScript API
  • WebAssembly- Manually write WebAssembly scripts

We welcome your attention and support