SDL2 backend corrupts memory after Sdl.PollEvent()

Hello,

I recently attempted move FreeSO to the latest development version of monogame, but I’m having an unusual error with SDL I just can’t shake. The game window opens, but then quickly closes afterwards. After pulling my hair out for about 4 hours straight, I was able to pin it down to the SDLGamePlatform.SdlRunLoop function, somehow making the “this” scope inaccessible:


For some reason, the Sdl.Event seems to be intact… When it returns 0, nothing bad happens.

This happens with both the bundled SDL2 x86, and the 2.0.4 x86 windows binary on their site. Stubbing out the function to handle SDL2 events leaves the game running as expected, but obviously without input…

Compiling https://github.com/FNA-XNA/SDL-mirror with VS2015 introduces a whole other error where the debugger just gives up (game seems to crash in same way when running without debugger).

The Monogame fork I’m running is the same as current develop, but with a DynamicSoundEffectInstance branch merged and some code to suppress an OpenTK garbage collection error.

I’m using VS2015 Enterprise, on Windows 10 x86. GPU is Intel HD Graphics 4600 + NVIDIA GTX 870M. Any ideas?

Well, I figured out what the problem is, but not why nobody else has encountered it.

The SDL_Event union is padded to 56 bytes to fit all the possible event types. The C# struct is much smaller than this max size, so it’s probably freaking out that the returned struct is too big. To fix the problem, I had to change:

[StructLayout(LayoutKind.Explicit)]
public struct Event
{
    [FieldOffset(0)] public EventType Type;
    [FieldOffset(0)] public Window.Event Window;
    [FieldOffset(0)] public Keyboard.Event Key;
    [FieldOffset(0)] public Keyboard.TextEditingEvent Edit;
    [FieldOffset(0)] public Keyboard.TextInputEvent Text;
    [FieldOffset(0)] public Mouse.WheelEvent Wheel;
    [FieldOffset(0)] public Joystick.DeviceEvent JoystickDevice;
}

to

[StructLayout(LayoutKind.Explicit, Size = 56)]
public struct Event
{
    [FieldOffset(0)] public EventType Type;
    [FieldOffset(0)] public Window.Event Window;
    [FieldOffset(0)] public Keyboard.Event Key;
    [FieldOffset(0)] public Keyboard.TextEditingEvent Edit;
    [FieldOffset(0)] public Keyboard.TextInputEvent Text;
    [FieldOffset(0)] public Mouse.WheelEvent Wheel;
    [FieldOffset(0)] public Joystick.DeviceEvent JoystickDevice;
}

(SDL2.cs : Line 53)

Game starts as normal now. :slightly_smiling:

1 Like

That information is very useful, thank you!!

2 Likes