首页 > 解决方案 > 无法在 emscripten 中绑定函数

问题描述

我正在尝试使用 emscripten 从 js 调用我的 c/c++ 函数。为此,我指的是本教程:https ://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/embind.html#embind

我正在遵循本文中提到的过程,但lerp函数没有被导出Module,我正在进入TypeError: Module.lerp is not a function我的浏览器控制台。

我只是使用本文中提到的文件,没有任何修改,但仍然无法从 js 调用 c 函数。

请帮助我我所缺少的

// 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);
}

索引.html

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

构建指令:

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

运行本地服务器

pyhton -m SimpleHTTPServer 9000

在浏览器上,启动此页面时,我收到此错误。

TypeError: Module.lerp is not a function

谢谢

标签: javascriptc++clangllvmemscripten

解决方案


初始化尚未完成。

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

推荐阅读