'Calling javascript function in c++ with emscripten embind

This question comes in two parts. What I want to do is to put most of my program logic in c++ classes and some view related function in js (like DOM manipulation and styling.) I use emscripten embind the classes and it works fine while I don't know how to interact with the js code (there are really limited resources on their tutorial.)

I was thinking to pass a val object to the c++ class according to their tutorial (https://github.com/kripken/emscripten/wiki/Tutorial) The passing works just fine while the "call" function doesn't work. I got a compile time error.

Here is the example I tried which they put on their tutorial:

#include <emscripten/val.h>
using namespace emscripten;

int main(){
  val Math = val::global("Math");
  Math.call("abs",-10);
  return 0;
}

and I got the following errors:

error: no matching member function for call to 'call'
    Math.call("abs",-10);
    ~~~~^~~~
emscripten/1.5.6/system/include/emscripten/val.h:247:21: note: candidate template ignored: couldn't infer template argument 'ReturnValue'
    ReturnValue call(const char* name, Args&&... args) const {

Basically it says the the compiler doesn't know the return type of the "call" function. Did I do anything wrong or is there a better way to interact with js code?

Thanks, yi



Solution 1:[1]

That's a common C++ problem. As a general rule, the following message should always make you double check in C++:

note: candidate template ignored: couldn't infer template argument 'ReturnValue' ReturnValue call(const char* name, Args&&... args) const

This mostly means that you tried to call a templated function but did not specify the necessary types.

If you look at the signature (in system/include/emscripten/val.h):

template<typename ReturnValue, typename... Args>
ReturnValue call(const char* name, Args&&... args) const

While it can infer Args quite fine, it has no idea, what ReturnValue might be. So calling this function should be done via e.g.:

Math.call<int>("abs",-10);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abergmeier