Try WebAssembly

wasm opened up a whole new field for the browser application. Significance, not to say a word or two to clear, just do a little experiment empty today.

 

1. emsdk installation

Emscripten directly to C / C ++ compiler is wasm, so that code is written in C can be run in a browser, or can not see the code that :)

Not too tangled how he packaged up and down anyway github directly from the latest source package can be used over:

download emsdk-master.zip

unzip emsdk-master.zip

cd emsdk-master

( emsdk-master update )

emsdk install latest

emsdk activate latest

Then add emsdk environment variables, additional direct me in the ~ / .bashrc last:

. (Front decompression path) /emsdk-master/emsdk_env.sh

Or you can directly copy the contents inside env.sh .bashrc to go inside.

------

This emsdk installation is complete.

------

If the middle of what's wrong, your system is estimated compilation tools Han incomplete installation due to:

sudo apt update
sudo apt install python2.7 nodejs build-essential cmake git-core default-jre

 

2. hello_world.html

Yes, emsdk support directly to your C code is compiled into a html file. Mainly because wasm not run directly in the browser, js need to load it, and then call her. The official directly compiled into * .html method that can reduce barriers to entry.

C code used:

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

Compiler directive:

emcc hello.c -o hello.html

Why can not because there is a direct hello.html run wasm, therefore, need from a web server. Fortunately it is emsdk also brought a server:

emrun --no_browser --port 8800 .

Or you can use directly python3 web server:

python3 -m http.server 8800

Then, in your browser, which you can see this result.

 

2. Write your own loader

The official html is really a bit ugly, we can also write their own loader, the function wasm are loaded over.

C function test:

 1 int fib(int n) {
  2     int i;
  3     int t;
  4     int a = 0;
  5     int b = 1;
  6 
  7     for(i = 0; i < n; i++) {
  8         t = a + b;
  9         a = b;
 10         b = t;
 11     }
 12 
 13     return b;
 14 }

Compile it into wasm module (do not ask me why, the official said, I did not study why):

emcc fib.c -Os -s WASM=1 -s SIDE_MODULE=1 -o fib.wasm

Then we can write their own pages to load it:

<html>
<body>
  <script>
    fetch('fib.wasm').then(response =>
      response.arrayBuffer()
    ).then(bytes =>
      WebAssembly.instantiate(bytes, {imports: {}})
    ).then(results => {
      window.fib = results.instance.exports.fib;
    });
  </script>
</body>
</html>

Open web server, and then open the browser a try.

Because the code above is just a function of wasm is introduced to javascript, so we have to perform this function need to open the debugging console:

Guess you like

Origin www.cnblogs.com/pied/p/11819291.html
try
Recommended