将JS函数传递给Emscripten生成的代码 [英] Passing JS function to Emscripten-generated code

查看:125
本文介绍了将JS函数传递给Emscripten生成的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段通过Emscripten转换为JavaScript的C ++代码。我希望转换后的C ++代码能够回调调用它的JavaScript代码。类似于:

I have a piece of C++ code converted to JavaScript via Emscripten. I would like the converted C++ code to call back to the JavaScript code that calls it. Something like:

JavaScript:

JavaScript:

function callback(message) {
    alert(message);
}

ccall("my_c_function", ..., callback);

C ++:

void my_c_function(whatever_type_t *callback) {
    callback("Hello World!");
}

这有可能吗?

推荐答案

我认为接受的答案有点过时了。

I believe the accepted answer is a bit outdated.

请参考与代码交互emscripten教程中的这一要点

例如
C:

E.g. C:

void invoke_function_pointer(void(*f)(void)) {
  (*f)();
}

JS:

var pointer = Runtime.addFunction(function() { 
  console.log('I was called from C world!'); 
});
Module.ccall('invoke_function_pointer', 'number', ['number'], [pointer]);
Runtime.removeFunction(pointer);

这样C代码就不需要知道它被转换成JS和任何所需的桥接器可以完全由JS控制。

This way the C-code does not need to be aware of that it is transpiled to JS and any bridges required can purely be controlled from JS.

(代码入侵消息编写器;可能包含错误)

这篇关于将JS函数传递给Emscripten生成的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆