This example package demonstrates compiling a simple C program, add.c
which adds two numbers to WASM, executing it in a host environment, and accessing it's methods.
- NodeJS & NPM is required to build the project dependencies, run the WASM compile, and run tests. NPM comes installed with NodeJS by default
- The EMCC compiler toolchain is required to compile C code to WASM
Before running the project, you must also install the project's dependencies:
npm install
src/
- Contains the C source code to be compiled into the WASM module, for example add.cbuild/
- Contains the compiled output WASM file resulting from the build processtest/
- Contains NodeJS test code demonstrating and unit testing the functionality contained in and exposed by the compiled WASM module inbuild
package.json
- Contains the dependency declarations and NPM build & test scripts. Controls WASM compiler options
- Write C Code with exported functions
- (if needed) Modify
package.json
's build script to include any new exported C functions (-s EXPORTED_FUNCTIONS=\"[...]\"
) - Compile the C code to WASM
- Modify tests in
test/
to test functionality exported from C - Run tests
- Repeat!
npm run build
An add.wasm
file will be produced in the build
directory
Test the module outside of the context of the blockchain:
npm test
How to access and use WASM modules from NodeJS, from test/add.unit.spec.js:
const util = require('../../../../src/util');
const buffer = fs.readFileSync(path.resolve(__dirname, '../build/add.wasm'));
const imports = util.getDefaultImports();
const result = await WebAssembly.instantiate(buffer, imports);
//use result.instance.exports to access functions prefixed by "_"
console.log(result.instance.exports._add(3, 99)); // => 102
Add two integers together and returns the result
Add an integer to a running total and returns the resulting running total