pauld pauld - 1 month ago 13
C++ Question

Add Javascript function to global scope

I have an emscripten application. I have a javascript file that has a function definition. I load that file into a string and then call

emscripten_run_script
on it. Then, I try to call that function later using some inline
EM_ASM
call, but it says the function definition can't be found.

std::ifstream file("script.js"); // script.js has "someFunc" defined
std::string str((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());

emscripten_run_script( str.c_str() );

// the below give error "someFunc not defined"
EM_ASM({
someFunc();
});


However, if I load that javascript file into a string and then append the string with the call to the function

std::ifstream file("script.js"); // script.js has "someFunc" defined
std::string str((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());

auto combinedStr = str + "someFunc();";

emscripten_run_script( combinedStr.c_str() ); // works fine


How can I add a javascript function defined in a file to global scope to be used later on?

The javascript file looks like this:
The javascript file looks like:

function someFunc()
{
}

Answer

In tests I've done this seems to work, which should be equivalent to what you've done:

#include <stdio.h>
#include <emscripten.h>

int main()
{
    char script[] = "someFunc = function() {"
                    "console.log(\"hello\");"
                    "};";

    emscripten_run_script(script);

    EM_ASM({
        someFunc();
    });
}

Is your script.js declaring the function to be local in scope (via var someFunc = function(){...}; or somesuch)? emscripten_run_script isn't exactly like JavaScripts eval and local variables only exist within the scope of emscripten_run_script.

Comments