Cocoa Nub
Cocoa Nub

Reputation: 499

Passing a C function pointer to emscripten callback

I'm using SDL2 with emscripten for a little game. I'm trying to pass a function pointer to free some memory if the browser tab is reloaded or closed as follows:

emscripten_set_beforeunload_callback(0, on_before_onload);

The on_before_onload function signature is defined thusly:

char *on_before_onload(int eventType, const void *reserved, void *userData);

I'm getting this warning:

incompatible function pointer types passing 'char *(int, const void *, void *)' to parameter of type 'em_beforeunload_callback' (aka 'const char *(*)(int, const void *, void *)') [-Wincompatible-function-pointer-types]
  emscripten_set_beforeunload_callback(0, on_before_onload);
  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I'm pretty new to C and am not fully grasping passing function pointers yet, apparently. I'm tried a bunch of different things to no avail.

It seems to call the function in Chrome, but not Safari even though the compiler complains.

How should I define the function?

Upvotes: 1

Views: 328

Answers (2)

ryyker
ryyker

Reputation: 23218

The error is telling you that the prototype for on_before_onload is not correct. According to this, it needs to be:

typedef const char *(*em_beforeunload_callback)(int eventType, const void *reserved, void *userData);

Where the parameters are defined as

    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.
  • Return type char *, returns a string to be displayed to the user.

Use typedefed function pointer created above (on_before_onload_fptr) to create on_before_onload in code location where it is in scope for use, perhaps main():

em_beforeunload_callback on_before_onload;

Then, elsewhere in code the actual function is defined according The new type:

char *on_before_onload(int eventType, const void *reserved, void *userData)
{
    char *retBuf = NULL;
    //code to handle event here
    return NULL;
}

Upvotes: 1

Evgeniy
Evgeniy

Reputation: 302

Before passing the pointer to function, you should declare the pointer to function like this:

char * ( *on_before_onload_fptr )(int, void *, void *) = on_before_onload

Upvotes: 0

Related Questions