JSWrap.hpp

Wrap a C++ function and convert it to an integer that can be called from Javascript.

To wrap a function, call:

uint32_t fun_id = JSWrap(FunctionToBeWrapped, "JS_Function_Name");`

To manually callback a function from Javascript, first set emp_i.cb_args to an array of function arguments, then call empCppCallback( fun_id ); This all happens automatically if you use the emp.Callback(fun_id, args...) function from Javascript.

The JS_Function_Name string is optional, but if you use it, the appropriate function will be automatically generated in Javascript by JSWrap, in the emp class.

For example, if you have:

int AddPair(int x, int y) { return x + y; }`

You can wrap it with:

size_t fun_id = JSWrap(AddPair, "AddPair");

And then in Javascript, you can simply call it as:

emp.AddPair(4, 5); // will return 9.

Todo:

Add a JSWrap that takes an object and method and does the bind automatically.

Build a non-enscripten version; it should still be callable from the C++ side, but mostly to be able to test programs without Emscripten.

Functions

template<typename FUN_TYPE>
size_t JSWrap(const FUN_TYPE &in_fun, const std::string &fun_name = "", bool dispose_on_use = false)

JSWrap takes a C++ function and wraps it in Javascript for easy calling in web code

Parameters:
  • in_fun – a C++ function to wrap

  • fun_name – optionally, a name to call the function on the Javascript size

  • dispose_on_use – should we delete this function after using it?

Returns:

the id of the function on the Javascript side

template<typename FUN_TYPE>
size_t JSWrapOnce(FUN_TYPE &&in_fun)

If we want a quick, unnammed, disposable function, use JSWrapOnce.

void JSDelete(size_t fun_id)

Cleanup a function pointer when finished with it.

void empDoCppCallback(const size_t cb_id)

This function is dispatched by empCppCallback. It should be dispatched on the thread hosting the main Empirical runtime. If running with Emscripten pthreads, that would be the worker thread hosting the main Empirical runtime. If not running with Emscripten pthreads, that would be the main browser thread. (In a few limited cases when running with Emscripten pthreads, this function is called on the main browser thread.)

void empCppCallback(const size_t cb_id)

Once you use JSWrap to create an ID, you can call the wrapped function from Javascript by supplying CPPCallback with the id and all args. If running with Emscripten pthreads, this method is to be called from the DOM and it will forward the call to empDoCppCallback on the web worker hosting Empirical runtime. If not running with Emscripten pthreads, this method simply calls empDoCppCallback (on the main browser thread).