Home  >  Q&A  >  body text

Pass JS functions to WASM

I'm reading a good book about WebAssembly and I'm trying to learn how to import JS functions into wasm without using "glue code".

This is a C file in which 2 extern functions are declared

extern int jsClearRect();
extern int jsFillRect();

I then compiled the c code into wasm using the following instructions:

emcc src/main.c -Os -s STANDALONE_WASM=1 -s SIDE_MODULE=1  -o main.wasm

I was then instructed to write a JS script which instantiate the wasm file, define jsFillRect() and jsClearRect() and import them using the import object to the env of the module.

// define the import Objects
const importObj = {
    "env": {
        "__memory_base":0,
        "tableBase":0,
        "memory": new WebAssembly.Memory({ initial: 256 }),
        "table": new WebAssembly.Table({ initial: 8, element: 'anyfunc' }),
        jsClearRect(): function() {/*function definition here*/},
        jsFillRect(): function() {/*function definition here*/},
    }
}
// import the module
fetch('main.wasm')
        .then(obj => WebAssembly.instantiateStreaming(obj,importObject))
        .then(result => console.log(result))
        .catch(err => console.log(err))

I received an error:

TypeError: import object field 'GOT.mem' is not an Object

The imported object I show here is already a modified version of the original object (which you can find here). In this example, the function is declared in JS as _jsClearRect(), but the module cannot find a definition for jsClearRect(). Then it can't find the definition of __memory_base because it was declared as memoryBase but now I don't know the king representation of Object GOT.mem​​ .

I've looked around and feel like I'm using an old API, but I can't find a suitable solution to achieve this.

So my question is:

How to import Javascript functions into the wasm module?

P粉081360775P粉081360775204 days ago295

reply all(1)I'll reply

  • P粉276876663

    P粉2768766632024-03-30 09:04:48

    GOT.mem​ From the dynamic link ABI used by emscripten. In this case I don't think you need dynamically linked content and you can/should remove -sSIDE_MODULE.

    This should simplify/reduce the imports you need to provide. (For example, you do not need to provide table or memory).

    reply
    0
  • Cancelreply