tmpvar.com wrench logo

POC / WASM strings

strings.cpp

// compile with:
// emcc -O2 --std=c++20 strings.cpp -s EXPORT_ES6=1 -lembind -o build/strings.js
#include <emscripten/bind.h>
#include <format>
#include <string>

using namespace emscripten;

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

std::string ReturnString(int value) {
  return std::format("whee value:{}", value);
}

EMSCRIPTEN_DECLARE_VAL_TYPE(CallbackType);

void CallMeBack(float value, CallbackType cb) {
  cb(std::format("callback time value:{}", value));
}

EMSCRIPTEN_BINDINGS(my_module) {
  function("lerp", &lerp);
  function("ReturnString", &ReturnString);
  function("CallMeBack", &CallMeBack);
  register_type<CallbackType>("(message: string) => void");
}

demo.js

import Module from './build/strings.js'

(async () => {
  const m = await Module();

  const outputEl = document.getElementById('output')
  function Log(content) {
    outputEl.innerText += content + '\n'
  }

  Log('lerp result: ' + m.lerp(1, 2, 0.5));
  Log(m.ReturnString(123));
  m.CallMeBack(1.5, (str) => {
    Log(`in CallMeBack cb "${str}"`)
  })

})();

output:



Notes

I originally wanted to do this using clang only, but ran into some issues related to the default NixOS clang-wrapper. In order to get something working, I tried emcc and later found embind which removes a bunch of the work.

Refs