The Emscripten tutorial give a good explanation of how to interact with C functions: https://github.com/kripken/emscripten/wiki/Interacting-with-code
But how do you interact with C++ classes:
Implement a C API in JavaScript. It is possible to implement a C API in JavaScript! This is the approach used in many of Emscripten's libraries, like SDL1 and OpenGL. You can use it to write your own APIs to call from C/C++.
Emscripten provides various options for connecting “normal” JavaScript and compiled code, which range from functions to call compiled C/C++ from JavaScript (and vice versa) through to accessing environment variables from compiled code.
Embind provides a C++ class, emscripten::val , which you can use to transliterate JavaScript code to C++. Using val you can call JavaScript objects from your C++, read and write their properties, or coerce them to C++ values like a bool , int , or std::string .
Module.ccall() calls a compiled C function from JavaScript and returns the result of that function. The function signature for Module.ccall() is as follows: ccall(ident, returnType, argTypes, args, opts) You must specify a type name for the returnType and argTypes parameters.
Check this : http://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/embind.html
Example :
C++ code :
#include <emscripten/bind.h>
using namespace emscripten;
class MyClass {
public:
MyClass(int x, std::string y)
: x(x)
, y(y)
{}
void incrementX() {
++x;
}
int getX() const { return x; }
void setX(int x_) { x = x_; }
static std::string getStringFromInstance(const MyClass& instance) {
return instance.y;
}
private:
int x;
std::string y;
};
EMSCRIPTEN_BINDINGS(my_class_example) {
class_<MyClass>("MyClass")
.constructor<int, std::string>()
.function("incrementX", &MyClass::incrementX)
.property("x", &MyClass::getX, &MyClass::setX)
.class_function("getStringFromInstance", &MyClass::getStringFromInstance)
;
}
JS code :
var instance = new Module.MyClass(10, "hello");
instance.incrementX();
instance.x; // 12
instance.x = 20; // 20
Module.MyClass.getStringFromInstance(instance); // "hello"
instance.delete();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With