[英]Add Javascript function to global scope
我有一個 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()
{
}
在我所做的測試中,這似乎有效,這應該等同於您所做的:
#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(){...};
或 somesuch)? emscripten_run_script
並不完全像 JavaScript 的eval
和局部變量只存在於emscripten_run_script
的范圍內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.