bottlenoselabs / SDL-cs

Automatically updated C# bindings for SDL v3 https://github.com/libsdl-org/SDL with native dynamic link libraries.
MIT License
16 stars 4 forks source link

Intended way to use callback functions? #492

Open Susko3 opened 8 months ago

Susko3 commented 8 months ago

How do you intend users to implement callback functions?

The shortest I could come up with is:

public static void Main()
{
    SDL_SetEventFilter(new FnPtr_VoidPtr_SDLEventPtr_Int { Pointer = &NativeFilter }, null);
}

[UnmanagedCallersOnly]
private static int NativeFilter(void* userdata, SDL_Event* e)
{
    // do work
    return 1;
}

which includes one implicit cast, so the actual complied code is

SDL_SetEventFilter(
    new SDL_EventFilter
    {
        Data = new FnPtr_VoidPtr_SDLEventPtr_Int
        {
            Pointer = &NativeFilter
        }
    },
    null);

The ideal situation would be just this, identical how this would be written in C:

SDL_SetEventFilter(&NativeFilter, null);
lithiumtoast commented 8 months ago

Ideally it can be done like you mentioned if your target is C#8 or above.

I have support for not using C#8 function pointers to which the code takes a delegate. The type FnPtr_X is useful in this situation. I didn't remove it or favor of removing the type altogether when adding support because function pointes were added after and didn't get around to it.