最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calling a function pointer with Emscripten - Stack Overflow

programmeradmin3浏览0评论

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

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
Share Improve this question asked Aug 29, 2014 at 21:22 Alba MendezAlba Mendez 4,6451 gold badge41 silver badges56 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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

https://github./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.

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.

发布评论

评论列表(0)

  1. 暂无评论