无法在 emscripten 中绑定函数

Not able to bind function in 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);
}

index.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

谢谢

我认为您需要将 lerp 函数放在 EXPORTED_FUNCTIONS 命令行选项中

EXPORTED_FUNCTIONS=['lerp']

此外,您可能希望在代码中使用 EMSCRIPTEN_KEEPALIVE 注释来防止内联,但 EXPORTED_FUNCTIONS 应该足够了。参见:

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

初始化尚未完成。

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

除了@zakki 的回答,在node 环境

中使用模块导入名称
const a = require("./quick_example.js")

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