Chapter 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 that your JavaScript code called into 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 figure 5.1 shows.

Figure 5.1. How the JavaScript code currently interacts 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 figure 5.2 shows.

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

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

  1. Use Emscripten macros. These include the emscripten_run_script series of macros, the EM_JS macro, and the EM_ASM series of macros.
  2. Add custom JavaScript to Emscripten’s JavaScript file that you can call into directly.
  3. Use function pointers in which the JavaScript code specifies a function for the module to call into. We’ll look at this approach in chapter 6.

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

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

Real-world use cases

Exercises

Summary

sitemap