chapter six

6 Creating a WebAssembly module that talks to JavaScript using function pointers

 

This chapter covers:

  • Adjusting C or C++ code to work with function pointers
  • Using Emscripten’s helper functions to pass JavaScript functions to the WebAssembly module
  • Calling function pointers in the WebAssembly module when not using Emscripten’s plumbing code

In chapter 5, you adjusted your module so that it was no longer passing a validation error message back to the JavaScript through a parameter. Instead, you modified the module so that it called a JavaScript function directly, as illustrated in figure 6.1.

Figure 6.1 The module calling a function in the JavaScript code

Imagine being able to pass a JavaScript function to the module based on the need of your JavaScript code at the time. When the module finishes processing, it can then call the function that was specified, as shown in figure 6.2.

Figure 6.2 The module calling a JavaScript function pointer

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

In this section, you’re going to build the C++ code for the validation logic. You’ll include the standard C library and Emscripten helper functions, which is the recommended way to build a module for use in production. Later in this chapter, you’ll learn the other approach to building a WebAssembly module that doesn’t include the standard C library or Emscripten helper functions.

6.1.1 Using a function pointer given to the module by JavaScript

6.1.2 Adjusting the C++ code

6.1.3 Compiling the code into a WebAssembly module

6.1.4 Adjusting the JavaScript code of the webpage

6.1.5 Viewing the results

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

6.2.1 Using function pointers given to the module by JavaScript

6.2.2 Making the C++ modifications

6.2.3 Compiling the code into a WebAssembly module

6.2.4 Adjusting the JavaScript that will interact with the module

6.2.5 Viewing the results

6.3 Exercises

6.4 Summary