WebAssembly Tutorial for Beginners
2022-4-17 05:36:13 Author: kalitut.com(查看原文) 阅读量:34 收藏

You need a WebAssembly tutorial? Get to know WebAssembly in under 15 minutes with this tutorial!

I will explain to you how easy it is to start with WebAssembly.

What is WebAssembly?

WebAssembly is a new way to safely and portably execute bytecode in the browser . Bytecode is superior in performance to JavaScript. Program types such as video editing, games or CAD are possible with WebAssemby and are very performant.

JavaScript

The programming languages ​​like Java , JavaScript or Python use an intermediate step to compile the code. This makes execution slower.

Java uses the Java byte code before translating the software into machine language. This step increases the portability of the software but slows down its execution.

New possibilities with WebAssembly?

WebAssembly is the first standard that enables computationally intensive applications in the browser. WebAssembly is making online gaming and video editing flourish . A video editing program can export the film at machine level and with multithreading.

WebAssembly has been a standardized for all major browser engines since 2017 . The W3C Consortium is working on improving WebAssembly to enable even more speed in new generations.

WebAssembly examples

WebAssembly is not only a theoretical wish, but some developers have used WebAssembly in different projects:

A collection of WebAssembly projects :

  1. Try this online video encoder to convert a video to a new format. You don’t have to install any new software, you can convert videos as soon as the website loads and your local computing power .
  2. Some gaming cravings? You can run an entire 3D game with fancy graphics and sound on your computer in a few seconds without downloading hundreds of gigabytes of data.
  3. Mozilla hosts a First Person Shooter that demonstrates what’s possible with WebAssembly –
  4. Do you have a picture that is too big? Use the resizer to resize your images.

Why is WebAssembly faster than JavaScript?

  • Load time : The wasm files have a small file size because they are written in machine code. The smaller file size reduces the WebAssembly loading time, which improves the loading performance of the entire website .
  • Execution time : Wasm execution time is equal to native machine code execution time -20% for the encapsulations ( security ). WebAssembly takes into account that the generated machine code runs safely. The overhead reduces performance by 20%. A parser first has to parse JavaScript , then a compiler checks whether a routine can still optimize the generated machine code ( TurboFan ).
  • Multithreading: JavaScript needs 1 core to execute the code . Your computer can only execute 1 statement at a time. Unlike JavaScript, Wasm lets you use the full power of multithreading .

When is WebAssembly a good choice?

WebAssembly isn’t a magic bullet, nor is it the best replacement for JavaScript. WebAssembly is not 100% optimized to modify the HTML Document Object Model (DOM) . Wasm’s application focus is on demanding and computationally intensive tasks, such as image manipulation and generation.

JavaScript is required to call Wasm functions. JavaScript should make simple changes to the user interface because the programming language was originally designed for this application.

WebAssembly Tutorial

  • Install the Emsscipten SDK .
  • Create C code with a few specifics to later reuse in WebAssembly.
  • Compile the C code to Wasm format via Emsscript SDK.
  • Build the HTML skeleton with a JavaScript function that calls the Wasm format.
  • Use a JavaScript function call that invokes machine code.

WebAssembly IDE

The WebAssemby.Studio is suitable for testing and trying out

On this website you can configure and compile a Hello World template . You don’t have to set anything up and can start programming straight away. With the online IDE, you can write C code, compile it and display it via the website.

This tutorial extends the Hello World project with a little more code .

Your C project in the browser

Create a Hello World template on https://webAssembly.studio

WebAssemblyStudio

Change the programming code:

In the Main.c

#include <stdio.h>
#include <sys/uio.h>
#include <math.h>

#define WASM_EXPORT __attribute__((visibility("default")))

/* WASM_EXPORT ist der Marker für JavaScript, sodass dieser diese die Funktion wiederfindet */
WASM_EXPORT
int powerer(int a, int b) {
  /*Du kannnst die volle Power von C in den Funktionen nutzen */
  return pow(a,b);
}


/* Noch eine Funktion für einen JavaScript-Aufruf */
WASM_EXPORT
int squareroot(int a) {
  return sqrt(a);
}


/* Funktion inde JavaScript zu finden ist*/
extern void putc_js(char c);

/* WASM Call - bitte nicht ändenr */ 
WASM_EXPORT
size_t writev_c(int fd, const struct iovec *iov, int iovcnt) {
  size_t cnt = 0;
  for (int i = 0; i < iovcnt; i++) {
    for (int j = 0; j < iov[i].iov_len; j++) {
      putc_js(((char *)iov[i].iov_base)[j]);
    }
    cnt += iov[i].iov_len;
  }
  return cnt;
}

JavaScript:

let x = '../out/main.wasm';

let instance = null;
let memoryStates = new WeakMap();

function syscall(instance, n, args) {
  switch (n) {
    default:
      // console.log("Syscall " + n + " NYI.");
      break;
    case /* brk */ 45: return 0;
    case /* writev */ 146:
      return instance.exports.writev_c(args[0], args[1], args[2]);
    case /* mmap2 */ 192:
      debugger;
      const memory = instance.exports.memory;
      let memoryState = memoryStates.get(instance);
      const requested = args[1];
      if (!memoryState) {
        memoryState = {
          object: memory,
          currentPosition: memory.buffer.byteLength,
        };
        memoryStates.set(instance, memoryState);
      }
      let cur = memoryState.currentPosition;
      if (cur + requested > memory.buffer.byteLength) {
        const need = Math.ceil((cur + requested - memory.buffer.byteLength) / 65536);
        memory.grow(need);
      }
      memoryState.currentPosition += requested;
      return cur;
  }
}

let s = "";
fetch(x).then(response =>
  response.arrayBuffer()
).then(bytes =>
  WebAssembly.instantiate(bytes, {
    env: {
      __syscall0: function __syscall0(n) { return syscall(instance, n, []); },
      __syscall1: function __syscall1(n, a) { return syscall(instance, n, [a]); },
      __syscall2: function __syscall2(n, a, b) { return syscall(instance, n, [a, b]); },
      __syscall3: function __syscall3(n, a, b, c) { return syscall(instance, n, [a, b, c]); },
      __syscall4: function __syscall4(n, a, b, c, d) { return syscall(instance, n, [a, b, c, d]); },
      __syscall5: function __syscall5(n, a, b, c, d, e) { return syscall(instance, n, [a, b, c, d, e]); },
      __syscall6: function __syscall6(n, a, b, c, d, e, f) { return syscall(instance, n, [a, b, c, d, e, f]); },
      putc_js: function (c) {
        c = String.fromCharCode(c);
        if (c == "\n") {
          console.log(s);
          s = "";
        } else {
          s += c;
        }
      }
    }
  })
).then(results => {
  instance = results.instance;

  /* Hier wird der Auruf von JavaScript in den C-Code gemacht*/
  document.getElementById("container").textContent = instance.exports.powerer(3,4);
}).catch(console.error);

Run the code

Build and run – WebAssembly Tutorial Coding

And see the output (Here for the Hello World project):

WebAssembly Tutorial

Alternatives for WebAssembly

The most well-known alternative for WebAssembly is JavaScript. JavaScript is slow, but almost every browser understands this type of programming.

TypeScript, Vue.js or JQuery are other alternatives. The developer has a different development experience, but the product is the same because a build script compiles them all to JavaScript.

TypeScript is the better JavaScript. Types, functions and classes enable Java-like programming. The typifications help you with orientation and the class structure creates an overview in the project.


文章来源: https://kalitut.com/webassembly-tutorial/
如有侵权请联系:admin#unsafe.sh