2014-08-29 128 views
4

使用Emscripten,是否可以从JavaScript调用函数指针(即数字)?
该函数的签名是可变的,所以我不能写一个帮手并完成。使用Emscripten调用函数指针

一个例子来说明,我有这样的函数:

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

回答

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。

+2

哇!我之前看过这个函数,我知道你可以用它们来调用一个指针,但是......我认为它们是罗马数字xD – 2014-08-30 21:27:55

0

我会创建一个C函数:

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

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

+0

正如我所说,我不能使用助手,因为签名是不固定的。在这种情况下,函数接受一个浮点数,但对于另一个函数,它可以接受两个整数等。 – 2014-08-30 09:16:09

+0

有没有办法调用函数指针而不必为每个可能的签名创建C函数? – 2014-08-30 09:16:27