emscripten - 如何使用 EM_JS 从 C++ 调用带有参数的 javascript 方法
问题描述
我刚刚完成了从 C/C++ 调用 JavaScript并按照他们的说明进行操作。我可以从 C++ 调用 Js 方法
C++
#include <iostream>
#include <string>
#include <emscripten.h>
#include <emscripten/bind.h>
EM_JS(void, call_js, (), {
jsMethod();
});
bool callJsBack()
{
call_js();
return true;
}
EMSCRIPTEN_BINDINGS(module)
{
emscripten::function("callJsBack", &callJsBack);
}
JS
<script>
var Module = {
onRuntimeInitialized: function() {
console.log('Module.callJsBack(): ' + Module.callJsBack());
}
};
function jsMethod() {
alert('I am a js method!');
}
</script>
我想让 jsMethod() 参数化(想在调用 jsMethod() 时从 C++ 传递字符串)。
function jsMethod(msg) {
alert(msg);
}
我没有找到任何示例或建议来实现此要求。
解决方案
找到了答案:
C++
EM_JS(void, call_js_agrs, (const char *title, int lentitle, const char *msg, int lenmsg), {
jsMethodAgrs(UTF8ToString(title, lentitle), UTF8ToString(msg, lenmsg));
});
bool callJsBackWithAgrs()
{
const std::string title = "Hello from C++";
const std::string msg = "This string is passed as a paramter from C++ code!";
call_js_agrs(title.c_str(), title.length(), msg.c_str(), msg.length());
return true;
}
EMSCRIPTEN_BINDINGS(module)
{
emscripten::function("callJsBackWithAgrs", &callJsBackWithAgrs);
}
JS:
var Module = {
onRuntimeInitialized: function() {
Module.callJsBackWithAgrs();
}
};
function jsMethodAgrs(title, msg) {
alert(title + '\n' + msg);
}
完整的工作示例: CallJsFromCpp
推荐阅读
- javascript - 纯 JS 仅将类添加到重复元素之一
- java - 如何将文件读入 Arraylist 并在 Java 中打印 ArrayList
- excel - 对除一张以外的所有工作表运行的 Excel 宏
- javascript - 如何使用firebase过滤UTC日期
- python - 如何解决 Plone 中依赖项之间的冲突?
- visualization - 您如何以一种方式表示响应时间和每秒请求数?
- reference - 问:NetSuite 电子商务 - 源自定义实体字段以参考结帐
- python - 如何在数据框中的列的单元格中取消嵌套 2x2 数组?
- mdx - 查询选定的维度成员(tostring)
- java - 使用java构建Web应用程序中的外来字母问题