Calling functions from a WebAssembly instance

We demonstrated how to call a function in a Wasm instance from JavaScript in the previous chapter, but that was assuming you instantiated a module in the browser with no glue code. Emscripten provides the ability to call functions from the Wasm instance as well. After a module is instantiated, you call functions by invoking them from the instance.exports object, which is accessible from the result of the resolved Promise. MDN's documentation provides the following function signature for WebAssembly.instantiateStreaming:

Promise<ResultObject> WebAssembly.instantiateStreaming(source, importObject);
You may need to use the WebAssembly.instantiate() method, depending on your browser. Chrome currently supports WebAssembly.instantiateStreaming(), but if you encounter an error when attempting to load your module, use the WebAssembly.instantiate() method instead.

The ResultObject contains the instance object that we need to reference to call exported functions from the module. Here's some code that calls a function named _addTwoNumbers from the compiled Wasm instance:

// Assume the importObj is already defined.
WebAssembly.instantiateStreaming(
fetch('simple.wasm'),
importObj
)
.then(result => {
const addedNumbers = result.instance.exports._addTwoNumbers(1, 2);
// result is 3
});

Emscripten provides a way to perform function calls in much the same way, albeit in a slightly different implementation. If you use the Promise-like API, you can access the function from an asm object that the promise of the Module() resolves with. The following example demonstrates how to utilize this functionality:

// Using Emscripten's Module
Module()
.then(result => {
// "asm" is essentially "instance"
const exports = result.asm;
const addedNumbers = exports._addTwoNumbers(1, 2);
// result is 3
});

Replicating the WebAssembly's Web API syntax with Emscripten simplifies any future refactoring. You can easily replace Module() with WebAssembly's instantiateStreaming() method and result.asm with result.instance in the future if you decide to use WebAssembly's Web API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset