Html5 - Tidbits

This page is meant to serve as an archive for assorted information regarding HTML5 development.

Exporting C functions to Javascript


Note

Disclaimer: this is a living document based on current research and experience. This currently does not work.


Somewhere in the project, define a global C function to be called by Javascript

extern "C"
{
#if PLATFORM_HTML5_BROWSER
DEFINE_LOG_CATEGORY_STATIC(LogHTML5, Log, All);
 
void my_func( const char* _string, int _number )
{
#ifdef __EMSCRIPTEN_TRACING__
    // Log to emscripten
    emscripten_log( EM_LOG_CONSOLE, TEXT("my_func( %s, %d )"), _string, _number );
#endif
 
    // Log to UE console
    UE_LOG( LogHTML5, Verbose, TEXT("my_func( %s, %d )"), _string, _number );
}
 
#endif 
}


Append the C function name with a prefixed '_' to this EXPORTED_FUNCTIONS array

// File
// <Engine>/Source/Programs/UnrealBuildTool/HTML5/HTML5ToolChain.cs(87)
 
Result += " -s EXPORTED_FUNCTIONS=\"['_main', '_resize_game', '_on_fatal', '_my_func']\" ";


The Javascript that handles the web interface gets pulled from a template during build, so any changes should be done to that.

// File
// <Engine>/Build/HTML5/GameX.html.template(223+)
var UE4 = {
    ...
    get my_func() {
        var fn = Module.cwrap('my_func', null, ['string'],['number'] );
        delete UE4["my_func"];
        UE4.my_func = fn;
        return fn;
    },
    ...
};
 
// Now anywhere inside Javascript, you can call
UE4.my_func("mystring", 1234);