Use WebAssembly to Share Memory Between Hosts and Modules

In this Shortcut, I’m going to introduce you to an important new WebAssembly concept called a Memory. This is an abstraction over the ability to address individual bytes stored in memory somewhere. In JavaScript-hosted environments like Node.js and the browser, we’d implement this as a TypedArray interface over a JavaScript memory buffer. These interfaces were introduced to make it possible for JavaScript applications to work more efficiently with 3D graphics in the browser and WebGL. They open the door to emulating pointer arithmetic, which is partially how C and C++ applications can function so seamlessly.

WebAssembly modules can create Memory instances if they need them for implementation purposes or if they wish to share them with their host environment. Conversely, the host environment can create the instance and the module can import it. In this Shortcut, we will import a Memory instance created by the host environment.

In the GitHub repository for this Shortcut, you should enter the directory 09-Memory.

We are going to learn some more about the WebAssembly instruction set as well. Normally we would use a higher-level language such as C++ or Rust, but to keep our attention focused on Memory instances, we will start with a text form of the module in fibonacci.wat, shown in the following code snippet. Notice that the first thing the module does is import a Memory ...

Get Use WebAssembly to Share Memory Between Hosts and Modules now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.