aga
aga

Reputation: 357

Not able to bind function in emscripten

I am trying to use emscripten to call my c/c++ function from js. For this, I am referring this tutorial : https://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/embind.html#embind

I am following the process mentioned in this article but lerp function is not getting exported to Module and I am getting TypeError: Module.lerp is not a function in my browser console.

I am just using the files mentioned in this article without any modification but still failing to call c function from js.

Please help me what I am missing

// quick_example.cpp
#include <emscripten/bind.h>

using namespace emscripten;

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

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

index.html

<!doctype html>
<html>
  <script src="quick_example.js"></script>
  <script>
    console.log('lerp result: ' + Module.lerp(1, 2, 0.5));
  </script>
</html>

build instruction :

emcc --bind -o quick_example.js quick_example.cpp

run local server

pyhton -m SimpleHTTPServer 9000

On browser, when launching this page, I am getting this error.

TypeError: Module.lerp is not a function

Thanks

Upvotes: 0

Views: 2815

Answers (3)

Asanka
Asanka

Reputation: 618

Additionally to @zakki's answer, use module import name in node environment

const a = require("./quick_example.js")

a['onRuntimeInitialized'] = () => {
...

Upvotes: 0

zakki
zakki

Reputation: 2353

Initialization isn't complete yet.

<!doctype html>
<html>
  <script src="quick_example.js"></script>
  <script>
  Module['onRuntimeInitialized'] = () => {
    console.log('lerp result: ' + Module.lerp(1, 2, 0.5));
  }
  </script>
</html>

Upvotes: 3

Graham Phillips
Graham Phillips

Reputation: 102

I think you need to put your lerp function in the EXPORTED_FUNCTIONS command line option

EXPORTED_FUNCTIONS=['lerp']

Also, you may want to use the EMSCRIPTEN_KEEPALIVE annotation in your code to prevent inlining, but EXPORTED_FUNCTIONS should be enough. See:

https://kripken.github.io/emscripten-site/docs/getting_started/FAQ.html#why-do-functions-in-my-c-c-source-code-vanish-when-i-compile-to-javascript-and-or-i-get-no-functions-to-process

Upvotes: -1

Related Questions