代码改变世界

其它方式实现JavaScript调用C++程序函数

2025-03-30 05:07  flyfish163  阅读(86)  评论(0)    收藏  举报

网上找了一篇文章

面向前端同学的 Emscripten WebAssembly 介绍(一) | Toyo

按照操作指引,尝试Js调用C++函数

直接跳到第二种方法:使用 Emscripten 官方提供的 Embind

 

按照作者示例代码,执行也会报错,提示Uncaught (in promise) TypeError: Module.add is not a function

 第二天

终于找到正确的指导网页,Thanks to the GOD

Embind — Emscripten 4.0.5-git (dev) documentation 

快速上手程序 及 运行示例如下

quick_example.cpp文件

    // 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);
    }
编译命令
emcc -lembind -o quick_example.js quick_example.cpp

 html文件

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

 

浏览器运行结果

 

还得是官方的Help管用!