5 Creating a WebAssembly module that calls into JavaScript

 

This chapter covers:

  • Calling into JavaScript directly using Emscripten’s toolkit
  • Calling into JavaScript without Emscripten’s toolkit

In chapter 4, you created a WebAssembly module where your JavaScript code called into it by using Emscripten’s ccall helper function. You passed a buffer as a parameter to the module’s function so that, if there was an issue, an error message could be returned by placing it into the buffer. If there was an issue, your JavaScript read the string from the module’s memory and then displayed the message to the user, as shown in figure 5.1.

Figure 5.1 The way the JavaScript code is interacting currently with the module’s functions

Imagine that rather than passing a buffer to the module’s function if there’s an issue, the module can just pass the error message directly to your JavaScript as shown in figure 5.2.

Figure 5.2 The module calling a function in the JavaScript code.

When using the Emscripten toolkit, there are three ways that you can interact with JavaScript code from your module:

5.1 Using C or C++ to create a module with Emscripten plumbing

5.1.1 Adjusting the C++ code

5.1.2 Creating the JavaScript that you want included in Emscripten’s generated JavaScript file

5.1.3 Compiling the code into a WebAssembly module

5.1.4 Adjusting the JavaScript code of the webpage

5.1.5 Viewing the results

5.2 Using C or C++ to create a module without Emscripten plumbing

5.2.1 Making the C++ modifications

5.2.2 Compiling the code into a WebAssembly module

5.2.3 Adjusting the JavaScript that will interact with the module

5.2.4 Viewing the results

5.3 Exercises

5.4 Summary