Search⌘ K
AI Features

Exports and Imports

Explore how WebAssembly modules manage exports and imports, enabling JavaScript integration and external function inclusion. Understand the structure of export and import sections, process of defining functions, and converting WASM text format into binary. This lesson helps you grasp the practical details of linking WebAssembly and JavaScript through exports and imports.

We'll cover the following...

A WebAssembly module consists of export and import sections. These sections are responsible for exporting functions out of and importing functions into the WebAssembly module.

Exports

In order to call the functions defined in a WebAssembly module from JavaScript, we need to export the functions from the WebAssembly module. The export section is where we’ll define all the functions that are exported out of the WebAssembly module.

Let’s go back to our classic add.wat example from the previous chapter:

Shell
(module
(func $add (param $lhs i32) (param $rhs i32) (result i32)
get_local $lhs
get_local $rhs
i32.add
)
(export "add" (func $add))
)

Here, we’ve exported the add function using the (export "add" (func $add)) statement. To export a function, we’ve used the export keyword followed by the name of the function and then the pointer to the exported function itself.

Remember that WebAssembly is compact-sized. Thus, we can represent the export statement along with the function definition itself:

Shell
(module
(func $add (export "add") (param $lhs i32) (param $rhs i32) (result i32)
get_local $lhs
get_local $rhs
i32.add
)
)

Let’s use WABT’s wat2wasm tool to convert the WebAssembly text format into a WebAssembly module with the following command:

C++
/path/to/build/directory/of/wabt/wat2wasm add.wat

Let’s analyze the generated byte code using the hexdump tool: ...