问题描述
我正在将SDL2和emscripten一起用于一个小游戏。如果尝试按以下方式重新加载或关闭浏览器选项卡,则尝试传递函数指针以释放一些内存:
emscripten_set_beforeunload_callback(0,on_before_onload);
因此定义了on_before_onload函数签名:
char *on_before_onload(int eventType,const void *reserved,void *userData);
我收到此警告:
incompatible function pointer types passing 'char *(int,const void *,void *)' to parameter of type 'em_beforeunload_callback' (aka 'const char *(*)(int,void *)') [-Wincompatible-function-pointer-types]
emscripten_set_beforeunload_callback(0,on_before_onload);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我对C还是很陌生,显然还没有完全掌握传递函数的指针。我尝试了很多不同的尝试,无济于事。
即使编译器抱怨,它似乎在Chrome中调用该函数,但没有在Safari中调用。
我应该如何定义功能?
解决方法
错误告诉您on_before_onload
的原型不正确。 According to this,必须为:
typedef const char *(*em_beforeunload_callback)(int eventType,const void *reserved,void *userData);
参数定义为
eventType (int) – The type of beforeunload event (EMSCRIPTEN_EVENT_BEFOREUNLOAD).
reserved (const void*) – Reserved for future use; pass in 0.
userData (void*) – The userData originally passed to the registration function.
- 返回类型
char *
,返回要显示给用户的字符串。
使用上面(on_before_onload_fptr
)创建的typedefed函数指针在可能使用的代码位置(可能是on_before_onload
)创建main()
:
em_beforeunload_callback on_before_onload;
然后,在代码的其他地方,根据新类型定义实际功能:
char *on_before_onload(int eventType,void *userData)
{
char *retBuf = NULL;
//code to handle event here
return NULL;
}
,
在将指针传递给函数之前,应声明函数指针,如下所示:
char * ( *on_before_onload_fptr )(int,void *,void *) = on_before_onload