使用Emscripten调用函数指针

时间:2014-08-29 21:22:04

标签: javascript emscripten

使用Emscripten,是否可以从JavaScript调用函数指针(因此,数字)? 函数的签名是可变的,因此我无法编写帮助程序并完成。

为了举例说明,我有这样的功能:

// Returns a function pointer to call, with the appropiate
// arguments, to initialize the demanded feature.
void* get_feature_activator(feature_t feat);

您应该按如下方式使用它:

// Initialize the speaker
void* activator = get_feature_activator(FEATURE_SPEAKER);
// We know this function needs one float, so we cast and call it
((void(*)(float))activator) (3.0);

使用JavaScript执行相同操作:

var activator = _get_feature_activator(constants.FEATURE_SPEAKER);
// TODO: Need to call this pointer with one float

2 个答案:

答案 0 :(得分:6)

您可以使用Runtime.dynCall从JS调用C函数指针。参见例如

https://github.com/kripken/emscripten/blob/ee17f05c0a45cad728ce0f215f2d2ffcdd75434b/src/library_browser.js#L715

参数为(type signature, pointer, array of arguments)。例如,类型' vi'表示返回void,接收一个整数参数。这对应于您可以在生成的代码中看到的FUNCTION_TABLE_vi。

答案 1 :(得分:0)

我会创建一个C函数:

void call_feature_activator(int activator, float in_val) {
  ((void(*)(float))activator) (in_val);
}

然后,您可以在JavaScript端调用该函数来触发激活器调用,它将处理回转到函数指针并调用它。