Is there a way to use C ++ in JavaScript?
From this I learned that JavaScript is written in C ++. I also figured out / deduced that most JavaScript is C ++ (like Math.atan+""
and Math.atan.toString()
leading to "function atan() { [native code] }"
). [native code
I'm assuming it's C ++, otherwise what would it be like to "hide" it?
My question is, is there a way to use C ++ in JavaScript? Should I use it in a function or JavaScript framework?
source to share
The emscripten project allows you to generate Javascript from C and C ++:
Emscripten is an LLVM-to-JavaScript compiler. Requires LLVM bitcode - which can be generated from C / C ++ using llvm-gcc (DragonEgg) or clang or any other language that can be converted to LLVM - and compiles this to JavaScript that can be run on the web (or else JavaScript might work).
and with methods like ccall and cwrap you can call C functions:
Using the example from the site, this is the C ++ code I used extern "C"
to prevent the name change:
#include <math.h>
extern "C" {
int int_sqrt(int x) {
return sqrt(x);
}
}
can be compiled like this:
./emcc tests/hello_function.cpp -o function.html -s EXPORTED_FUNCTIONS="['_int_sqrt']"
and used in Javascript:
int_sqrt = Module.cwrap('int_sqrt', 'number', ['number'])
int_sqrt(12)
int_sqrt(28)
embind can be used for C ++ functions and classes. A quick example from the site looks like this:
// 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);
}
and compile:
emcc --bind -o quick_example.js quick_example.cpp
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>
source to share