Here are our files in project:

➜  wasmCTest ls
index.html  lib.c  lib.wasm

Add a simple C function in lib.c:

#include <stdio.h>

// export the function.
#ifdef __EMSCRIPTEN__ 
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
#endif
int compute( int a, int b )
{
    int ans = 1;
    for( int i = 0; i < b; ++i )
    {
        ans = ans * a;
    }
    return ans;
}

Get wasm without glue js file

emcc -O2 -s WASM=1 -s SIDE_MODULE=1 lib.c -o lib.wasm

Download the wasm file and use the interface in html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>WASM Demo</title>
  </head>
  <body>
    <script>

      // to get wasm without glue js file: emcc -O2 -s WASM=1 -s SIDE_MODULE=1 lib.c -o lib.wasm
      let imports = {
        env: {
          //log_number: (number) => console.log(`Number from Rust: ${number}`)
        }
      };
      fetch('lib.wasm')
        .then((response) => response.arrayBuffer())
        .then((bytes) => WebAssembly.instantiate(bytes, imports))
        .then((result) => {
          var outLog = result.instance.exports.compute(2, 3);
          console.log( "outLog: ", outLog );
        });
    </script>
  </body>
</html>

Result:

outLog:  8
Categories: Web

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Explain Code
: explain the code you input to help you to understand it.

X
0
Would love your thoughts, please comment.x
()
x