有没有办法在JavaScript中使用C ++? [英] Is there a way to use C++ in JavaScript?
问题描述
从此中,我发现JavaScript是用C ++编写的.我还发现/推断出大多数JavaScript是C ++(例如 Math.atan +"
和 Math.atan.toString()
产生"function atan(){[本地代码]}"
).我假设 [native code
是C ++,否则隐藏"它的意义是什么?
From this, I found out that JavaScript is written in C++. I also have found out/deduced that a majority of JavaScript is C++ (e.g. Math.atan+""
and Math.atan.toString()
yielding "function atan() { [native code] }"
). The [native code
I assume to be C++, else what would be the point of 'hiding' it?
我的问题是有没有办法在JavaScript中利用C ++?要在函数中还是在JavaScript平台中使用它?
My question is there a way to utilize C++ in JavaScript? To use it in a function or in the JavaScript platform?
推荐答案
emscripten 项目可让您从C和C ++生成Javascript:
The emscripten project allows you to to generate Javascript from C and C++:
Emscripten是LLVM到JavaScript的编译器.它需要LLVM位代码-可以使用llvm-gcc(DragonEgg)从C/C ++生成,也可以lang声或可以转换为LLVM的任何其他语言-和将其编译为JavaScript,可以在网络上运行(或其他可以运行JavaScript的地方.
Emscripten is an LLVM-to-JavaScript compiler. It takes LLVM bitcode - which can be generated from C/C++, using llvm-gcc (DragonEgg) or clang, or any other language that can be converted into LLVM - and compiles that into JavaScript, which can be run on the web (or anywhere else JavaScript can run).
并通过调用和cwrap 您可以调用C函数:
and through methods like ccall and cwrap you can call C functions:
使用该站点中的示例,该C ++代码使用 extern"C"
来防止名称篡改:
Using the example from the site, this C++ code which used extern "C"
to prevent name mangling:
#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中使用:
and used in Javascript:
int_sqrt = Module.cwrap('int_sqrt', 'number', ['number'])
int_sqrt(12)
int_sqrt(28)
embind 可以用于C ++函数和类.该站点的快速示例如下:
embind can be used for C++ functions and classes. The quick example from the site is as follows:
// 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中使用:
and use in Javascript:
<!doctype html>
<html>
<script src="quick_example.js"></script>
<script>
console.log('lerp result: ' + Module.lerp(1, 2, 0.5));
</script>
</html>
这篇关于有没有办法在JavaScript中使用C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!