DEV Community

Matt Tarasov
Matt Tarasov

Posted on

1

How to pass custom module from JS to C++

Passing custom module from JS to C++ code with Emscripten is the easier task than it seems!
I created a tiny example to show how to pass module from JS to C++ using Emscripten and val::global()

First of all we need to write a C++ function for the loading. It looks like this:

int loadCustomModule (std::string globalModuleName) {
  val ModuleClass = val::global(globalModuleName.c_str());
    if (!ModuleClass.as<bool>()) {
    std::cout << "No global module " << globalModuleName;
  }
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Then we need to pass this function to JS using EMSCRIPTEN_BINDINGS:

EMSCRIPTEN_BINDINGS(module) {
  function("loadCustomModule", &loadCustomModule);
}
Enter fullscreen mode Exit fullscreen mode

Yeah, that's all! Now, we can use our loadCustomModule function in JS.

class HelloWorldCustomModule {
    helloWorld() {
        console.log('Hello, World!')
    }
}
var Module = {
    onRuntimeInitialized: function () {
        window.HelloWorldCustomModule = HelloWorldCustomModule;
        Module.loadCustomModule('HelloWorldCustomModule')
    }
};
Enter fullscreen mode Exit fullscreen mode

And the last step is using our HelloWorldCustomModule in C++

int loadCustomModule (std::string globalModuleName) {
  // ... first part is above
  val module = ModuleClass.new_();
  module.call<val>("helloWorld");
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Compilation

em++ -lembind -o passCustomModule.js passCustomModule.cpp -s ERROR_ON_UNDEFINED_SYMBOLS=0 -Wall --bind
Enter fullscreen mode Exit fullscreen mode

The full example with HTML you can find there

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay