将JavaScript函数添加到全局范围

3

我有一个使用emscripten编写的应用程序。我有一个包含函数定义的javascript文件。我将该文件加载到一个字符串中,然后调用emscripten_run_script。稍后,我尝试使用一些内联的EM_ASM调用来调用该函数,但是它显示找不到函数定义。

    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();
    });

然而,如果我将该JavaScript文件加载到字符串中,然后使用函数调用附加该字符串。
    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

如何将一个定义在文件中的javascript函数添加到全局作用域以便稍后使用?

这个javascript文件看起来像这样:

function someFunc()
{
}
1个回答

2
在我所做的测试中,这似乎是有效的,应该等同于您所做的:
#include <stdio.h>
#include <emscripten.h>

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

    emscripten_run_script(script);

    EM_ASM({
        someFunc();
    });
}

你的 script.js 是否通过 var someFunc = function(){...}; 等方式将函数声明为局部变量?emscripten_run_script 与 JavaScript 的 eval 不完全相同,局部变量仅存在于 emscripten_run_script 的范围内。

谢谢,只需将"function someFunc()"更改为"someFunc = function()"就可以了! - default

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接