Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interaction with C++ classes in Emscripten

Tags:

emscripten

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:

  • Call a constructor to create an object
  • Delete an obj
  • Prevent dead code elimination of classes and its methods
like image 291
Mortennobel Avatar asked Apr 07 '13 18:04

Mortennobel


People also ask

Can you use C with JavaScript?

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++.

Can you connect C++ to JavaScript?

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.

How do you use Embind?

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 .

What is module Ccall?

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.


1 Answers

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();
like image 145
Zardoz89 Avatar answered Nov 15 '22 05:11

Zardoz89