3

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:

function someFunc()
{
}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, simply changing from "function someFunc()" to "someFunc = function()" did the trick!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.