Calling a function pointer with Emscripten

主宰稳场 提交于 2019-12-10 17:08:59

问题


With Emscripten, is it possible to call a function pointer (thus, a number) from 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:

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

回答1:


You can call a C function pointer from JS using Runtime.dynCall. See for example

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

The arguments are (type signature, pointer, array of arguments). For example, the type 'vi' means return void, receive one integer parameter. This corresponds to FUNCTION_TABLE_vi which you can see in the generated code.




回答2:


I would create a C function:

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.



来源:https://stackoverflow.com/questions/25576458/calling-a-function-pointer-with-emscripten

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!