Listing 1: wat-Repräsentation eines Was-Moduls

;; this module defines function
;; that calculates the sum of two 32-bit
;; numbers and returns the  result

;;module declaration
(module
	;;import function "log" from browser
	(import "env" "log" (func $log))

	;;declaration of function "sum"
    (func $sum (param $firstNo i32) (param $scndNo i32) (result i32)
	 ;;add first param to stack
     get_local $firstNo
     ;;add second param to stack
	 get_local $scndNo
     ;;add the numbers on the stack
     i32.add
     ;;call the imported log-function
     call $log
	 ;;return the value from the current stack
     return
	)

	;;export function "sum" to browser
	(export "sum" (func $sum))
)


Listing 2: wat im Zusammenspiel mit Docker

Windows:
docker run -it --rm -v %cd%:/data -w /data jungomi/wabt wat2wasm ./example.wat  -o ./example.wasm
Unix:
docker run -it --rm -v $PWD:/data -w /data jungomi/wabt wat2wasm ./example.wat  -o ./example.wasm 

Listing 3: Compile API
(async () => {
    const myAgeModule = await WebAssembly.compileStreaming(fetch('./my_age.wasm'));
    //module can now be instantiated, cached, passed to a worker etc.

    //get meta-information about the module
    WebAssembly.Module.exports(myAgeModule); // [{name: "getMyAge", kind: "function"}]
    WebAssembly.Module.imports(myAgeModule); // []
})();

Listing 4: Instantiate
(async () => {
    const myAgeModule = await WebAssembly.compileStreaming(fetch('./my_age.wasm'));

    //returns the instance
    const instanceA = await WebAssembly.instantiate(myAgeModule);
    console.log(instanceA.exports); // {getMyAge: Function}

    // returns the compiled module AND the instance
    const {instance, module} = await WebAssembly.instantiateStreaming(fetch('./wasm/my_age.wasm'));
    console.log(instance.exports); // {getMyAge: Function}

    //call the exported function
    console.log(instance.exports.getMyAge());
})();


​
Listing 5: Instantiate with imports
​(async () => {
    const {instance} = await WebAssembly.instantiateStreaming(fetch('./example.wasm'), {
        env: {
            //env-object contains all imports
            log: () => console.log('HI!!!')
        }
    });
    console.log(instance.exports.sum(30, 2)); // HI!!! 32
})();

Listing agent 6: check_primes.c
int isPrime(int num) {
  for (int i = 2; i < num; i++) {
    if (num % i == 0) {
      return 0;
    }
  }
  return (num != 1 && num != 0) ? 1 : 0;
}


int checkPrimes(int maxNumber) {
  int count = 0;
  for (int i = 0; i < maxNumber; i++) {
    if (isPrime(i) == 1) {
      count++;
    }
  }
  return count;
}

Listing 7: emscripten
Windows:
docker run --rm -v %cd%:/data -it trzeci/emscripten emcc -g /data/check_primes.c -s SIDE_MODULE=1 -Oz -s EXPORTED_FUNCTIONS=['_checkPrimes'] -o /data/checkPrimes.wasm"
Unix:
docker run --rm -v $PWD:/data -it trzeci/emscripten emcc -g /data/check_primes.c -s SIDE_MODULE=1 -Oz -s EXPORTED_FUNCTIONS=['_checkPrimes'] -o /data/checkPrimes.wasm"

Listing 8: JavaScript initialize
(async () => {
    const {instance} = await WebAssembly.instantiateStreaming(fetch('./checkPrimes.wasm'), {
        env: {
            __memory_base: 0
        }
    });
    console.log(instance.exports._checkPrimes(123));
})();

Listing 8: JavaScript initialize
(async () => {
    const {instance} = await WebAssembly.instantiateStreaming(fetch('./checkPrimes.wasm'), {
        env: {
            __memory_base: 0
        }
    });
    console.log(instance.exports._checkPrimes(123));
})();

Listing 9: emscripten js code
//compile with emscripten:
docker run --rm -v %cd%:/data -it trzeci/emscripten emcc -g /data/c/check_primes.c -s -Oz -s EXPORTED_FUNCTIONS=['_checkPrimes'] -o /data/checkPrimes.js",

<script src="./checkPrimes.js"></script>
<script>
    Module.onRuntimeInitialized = () => {
        console.log(Module._checkPrimes(123));
    };
</script>

Listing 10: primes_with log
//...
extern void logPrime(int prime);

int checkPrimes(int maxNumber) {
  int count = 0;
  for (int i = 0; i < maxNumber; i++) {
    if (isPrime(i) == 1) {
      logPrime(i);
      count++;
    }
  }
  return count;
}

Listing 11: js usage
(async () => {
    const {instance} = await WebAssembly.instantiateStreaming(fetch('./dist/checkPrimes_and_log.wasm'), {
        env: {
            __memory_base: 0,
            _logPrime: currentPrime => console.log('Found prime', currentPrime)
        }
    });
    console.log(instance.exports._checkPrimes(123));
})();

Listing 12: C COde + JS Code String return
//hello.c
const char* sayHello() {
    return "Hello world from Wasm";
};

//javascript
(async () => {
    const memory = new WebAssembly.Memory({initial: 256, maximum: 512});
    const readableBuffer = new Uint8Array(memory.buffer);

    const {instance} = await WebAssembly.instantiateStreaming(fetch('./dist/hello.wasm'), {
        env: {
            __memory_base: 0,
            memory
        }
    });

    console.log(readableBuffer); // [72, 101, 108, 108, 111,...]
    const pointer = instance.exports._sayHello(); //points to specific index in the memory-view, e.g. 0
    console.log(readString(readableBuffer, pointer)); //convert the bytes to a string using some helper function
})();

Listing 13: String-Binding mit Emscripten
<script src="./hello_glue.js"></script>
<script>
    Module.onRuntimeInitialized = () => {
        //wrap the function. Second parameter defines the return value
        const sayHello = cwrap('sayHello', 'string');
        console.log(sayHello());
    };
</script>