[英]Is there a way to use C++ in JavaScript?
由此,我发现 JavaScript 是用 C++ 编写的。 我还发现/推断出大部分 JavaScript 是 C++(例如Math.atan+""
和Math.atan.toString()
产生"function atan() { [native code] }"
)。 [native code
我假设是 C++ 的[native code
,否则“隐藏”它有什么意义?
我的问题是有没有办法在 JavaScript 中使用 C++? 在函数或 JavaScript 平台中使用它?
emscripten项目允许您从 C 和 C++ 生成 Javascript:
Emscripten 是一个 LLVM 到 JavaScript 的编译器。 它需要 LLVM 位码——可以从 C/C++ 生成,使用 llvm-gcc (DragonEgg) 或 clang,或任何其他可以转换为 LLVM 的语言——并将其编译成 JavaScript,可以在网络上运行(或JavaScript 可以运行的任何其他地方)。
通过像ccall 和 cwrap这样的方法,你可以调用 C 函数:
使用站点中的示例,此 C++ 代码使用extern "C"
来防止名称修改:
#include <math.h>
extern "C" {
int int_sqrt(int x) {
return sqrt(x);
}
}
可以这样编译:
./emcc tests/hello_function.cpp -o function.html -s EXPORTED_FUNCTIONS="['_int_sqrt']"
并在 Javascript 中使用:
int_sqrt = Module.cwrap('int_sqrt', 'number', ['number'])
int_sqrt(12)
int_sqrt(28)
embind可用于 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);
}
并编译:
emcc --bind -o quick_example.js quick_example.cpp
并在 Javascript 中使用:
<!doctype html>
<html>
<script src="quick_example.js"></script>
<script>
console.log('lerp result: ' + Module.lerp(1, 2, 0.5));
</script>
</html>
您可以使用 NACL。 它是 chrome 的本机客户端,但它是实验性的。 你必须编写 C++ 代码,然后在你的 JS 文件中引用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.