首页 > 解决方案 > 如何使用 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);
}

我没有找到任何示例或建议来实现此要求。

标签: emscriptenwebassembly

解决方案


找到了答案:

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


推荐阅读