简体   繁体   English

使用Emscripten调用函数指针

[英]Calling a function pointer with Emscripten

With Emscripten, is it possible to call a function pointer (thus, a number) from JavaScript? 使用Emscripten,是否可以从JavaScript调用函数指针(因此,一个数字)?
The signature of the function is variable, so I can't write a helper and be done. 函数的签名是可变的,所以我不能编写帮助程序并完成。

To illustrate an example, I've got a function like this: 为了举例说明,我有一个这样的函数:

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

You're supposed to use it as follows: 您应该按如下方式使用它:

// 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);

To do the same with JavaScript: 要对JavaScript执行相同的操作:

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

You can call a C function pointer from JS using Runtime.dynCall . 您可以使用Runtime.dynCall从JS调用C函数指针。 See for example 例如,参见

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

The arguments are (type signature, pointer, array of arguments) . 参数是(type signature, pointer, array of arguments) For example, the type 'vi' means return void, receive one integer parameter. 例如,类型'vi'表示返回void,接收一个整数参数。 This corresponds to FUNCTION_TABLE_vi which you can see in the generated code. 这对应于您可以在生成的代码中看到的FUNCTION_TABLE_vi。

I would create a C function: 我会创建一个C函数:

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

You can then call the function on the JavaScript side to trigger your activator call and it will handle casting back to a function pointer and calling it. 然后,您可以调用JavaScript端的函数来触发激活器调用,它将处理回退到函数指针并调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM