I am learning about emscripten and trying to understand it better. As far as I understand the use-case it was mostly designed for is to port existing C/C++-code to a web client (browser) and calling C/C++ code from JavaScript.
But I am wondering whether it is possible to use C++ and Emscripten to web page (note: this is more out of curiosity - I know that there are not many good reasons to do that at the moment). I manage to call Javascript functions from C++ and pass arguments of types string, int, double etc to them. But what I am missing is: calling a Javascript function from C++ and passing a C or C++ function as a handle. So as a simple example: How would I write the following Javascript code ind pure C++?
var myfun = function() { /* do something meaningful here */ }
document.onload(myfun);
I'm not sure about emscripten, but to sum up, I understand that what you need to know is how to pass a C++ function as a handle to another C++ function. I hope I can help with that.
JavaScript, PHP, and other more flexible languages, allow a function object to be passed through. In C and C++, it is slightly different, you have to pass function pointers as arguments to other functions. In C, the name for this is a Callback, rather than a handle.
For instance:
It is a common practice to create a custom type to the argument, so you don't need to use something as ugly as
int (*numberSource)(void)
. It will be something like:So the printNumber function would be like this:
So, in your case, if you want to translate this JS code
to C, and you have a C object called "document" that receives a function that performs some other actions, your C code will be: