Location>code7788 >text

WebAssembly Basics and Combining Other Programming Languages

Popularity:934 ℃/2024-10-13 20:52:14

0x00 WebAssembly Basics

For more details, please refer to《WebAssembly | MDN》

(1) Overview

  • WebAssembly, abbreviated as WASM or WA, is a new way of coding that runs in modern web browsers.
  • Code written in multiple programming languages (e.g., C/C++, C#, Go, Python, Rust, TypeScript, etc.) can be converted to WA through a compiler and used in a browser
  • Features:
    • Highly flexible: a low-level assembly-like language
    • Smaller size: with a compact binary format
    • Performance Improvement: Near-native performance runs
  • WA can coexist with JavaScript, allowing the two to work together.
  • WA Key Concepts:
    • Module: represents a WA binary code that has been compiled by the browser into executable machine code.
    • Memory: a variable-lengthArrayBuffer
    • Table: A variable-length typed array
    • Example: a module and all the state it uses at runtime (including memory, tables and a range of imported values)
  • Related applications written using WA:Figma et al. (and other authors)

(2) Load and Run

  1. Typically, the compiler compiles code from other languages into the.wasm file for use in a WA environment

  2. In the browser environment, you can import external files via AJAX, such as importing the.wasm file

    fetch("");
    
  3. JavaScriptWebAssembly object is the namespace for all WA-related functions, where the / maybe / Method combinations can be used to load and run WA code

    fetch("")
      .then((response) => ())
      .then((bytes) => (bytes))
      .then((module) => {
        const instance = new (module);
        ();
      });
    

    maybe

    (fetch("")).then(
      (results) => {
        const instance = ;
        ();
      },
    );
    

(3) Related JavaScript APIs

  • WebAssembly: Namespace for all WA-related functions

a. Objects

  • : Contains stateless WebAssembly code that has already been compiled by the browser.
  • : a global variable instance that can be accessed by JavaScript and importable/exportable
  • : there are states that are An executable instance of
  • : JavaScript wrapper representing the concept of a WA form, with a class array structure storing multiple function references.
  • : Defines a type of WA exception that can be thrown from or to WA code.
  • : Indicates a runtime exception thrown from WA to JavaScript, or from JavaScript to the WA exception handler.
  • : Indicates that an error occurred during module instantiation

b. Methodology

  • (): used to create a newMemory memory object
  • (): Create a new WA compilation error object
  • (): Create a new WA runtime error object

0x01 Combining C/C++

  1. Write a piece of code in C or C++ (in C for example)

    // filename: 
    #include<>
    
    int main(){
      printf("Hello, WebAssembly!");
      return 0;
    }
    

    Run the test without error and continue

  2. Download and install theEmscripten

    Refer to the official download and installation documentation for details:/docs/getting_started/

  3. Using Commandsemcc -s WASM=1 -o compiling

    • emcc: Tools provided by Emscripten
    • : C-based code
    • -s WASM=1: Specify the output WA
    • -o : Outputs, and files, on demand

0x02 Combining C#

  1. Write a piece of code in C#

    // filename: 
    public class Example
    {
      public static void Main()
      {
        ("Hello, WebAssembly!");
      }
    }
    
  2. Install the .NET Core SDK, mono

  3. Using Commandsmcs --out: -t:library Compiling C# Code into a DLL

  4. Using Commandsmono --runtime=mono --aot=llvm Compiling a DLL into a WA

0x03 Combining Go

  1. Write a piece of code using Go:

    // filename: 
    package main
    
    import "fmt"
    
    func main() {
      ("Hello, WebAssembly!")
    }
    
  2. Using CommandsGOOS=js GOARCH=wasm go build -o Compiled as

0x04 Combining Python

  • Python can be compiled into WA with the py2wasm utility, or Python can be executed directly in JavaScript using pyodide.

a. py2wasm

  1. Write a piece of code using Python:

    # filename: 
    if __name__ == '__main__':
        print("Hello, WebAssembly!")
    
  2. Using Commandspip install py2wasm Install the py2wasm tool

  3. Using Commandspy2wasm -o Compiles the

b. pyodide

Importing and writing Python code in the HTML header

<!DOCTYPE html>
<html>
  <head>
    <script src="/pyodide/v0.26.0/full/"></script>
  </head>

  <body>
    <script>
      async function main() {
        let pyodide = await loadPyodide();
        await ("numpy"); // Load a Python storehouse
        let result = await (`
                import numpy as np
                ([1, 2, 3, 4])
            `);
        (result);
      }
      main();
    </script>
  </body>
</html>

If you are in a NodeJS environment, you can use the commandnpm install pyodide import (data)

0x05 Combining Rust

referenced fromCompiling Rust code into WASM | blogspot-_zhiqiu

  1. Using Commandscargo add wasm-bindgen Adding dependencies

  2. Using Commandsrustup target add wasm32-unknown-unknown installation target

  3. Write a piece of code using Rust:

    // filename:
    use wasm_bindgen::prelude::*;
    
    // utilization #[wasm_bindgen] macro to export a function to the JavaScript
    #[wasm_bindgen]
    pub fn greet(name: &str) -> String {
      format!("Hello, {}!", name)
    }
    
  4. Using Commandscargo build --target wasm32-unknown-unknown --release Compile to etc.

  5. Using Commandswasm-bindgen --out-dir ./out --target web target/wasm32-unknown-unknown/release/lib_wasm.wasm Generate a JavaScript binding file and set the output directory to./out

0x06 Combining TypeScript

  • AssemblyScript, abbreviated AS, compiles strict variants of TypeScript into WA.
  • Specific operation method referenceAS Official Documentation

-End-