Table of contents

  1. Binary heap tree proof: index of left child is doubled index of parent + 1

    January 2022

  2. emscripten + node.js

    December 2021

Content

emscripten + node.js

For some reasons I couldn’t find this info easily. For debugging purposes it would be nice to be able to connect C++ code with node.js. Official emscripten documentation explains how to run code in browser. But node.js works differently. Let’s create a simple C++ file:

main.cpp

#include "main.h"

float lerp(float a, float b, float t) {
    return (1 - t) * a + t * b;
}

main.h:

float lerp(float a, float b, float t);

It will not have any emscripten-related code, so I could use my IDE normally, without it knowing about any emscripten at all 🙂 Okie, let’s go:

emscripten.cpp


#include <emscripten/bind.h>
#include "main.h"

using namespace emscripten;

EMSCRIPTEN_BINDINGS(my_module) {
    function("lerp", &lerp);
}

Now we need to compile the code into a js code:

emcc -s WASM=0 --bind -o main.js -s EXPORT_ES6 -s ENVIRONMENT=shell embindings.cpp main.cpp

package.json

{
  "name": "untitled",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "type": "module"
}

index.js

import wasmModule from './main.js';

const instance = await wasmModule();

console.log(instance.lerp(0, 1, 0.5));

Also a note about some flags:

-s DISABLE_EXCEPTION_CATCHING=0

-s ALLOW_MEMORY_GROWTH=1

-s O1 is the maximum optimization level allowed. -s O2, -s O3 and -s Os result in a run-time fail of module importing.