【问题标题】:Not able to bind function in emscripten无法在 emscripten 中绑定函数
【发布时间】:2018-07-14 21:12:56
【问题描述】:

我正在尝试使用 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

谢谢

【问题讨论】:

  • 你的代码在哪里?
  • 已添加,请查看
  • quick_example.js的内容是什么
  • 我不熟悉 emscripten,但我注意到您使用的是“Module.lerp”,而您传递给 EMSCRIPTEN_BINDINGS 的是 my_module。
  • @zneak 是的,但这是在原始文档中。可能有错误的文档?

标签: javascript c++ clang llvm emscripten


【解决方案1】:

初始化尚未完成。

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

【讨论】:

    【解决方案2】:

    我认为您需要将 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

    【讨论】:

      【解决方案3】:

      除了@zakki 的回答,在node 环境中使用模块导入名称

      const a = require("./quick_example.js")
      
      a['onRuntimeInitialized'] = () => {
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-29
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多