Failed to load SDL2 on Linux through P/Invoke method call

I’m changing my code to save and load my game’s save file from the SDL preference path instead of the game folder. I accomplished it with the following:

[DllImport("SDL2", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr SDL_GetPrefPath(string org, string app);

This works perfectly fine on Windows, but on Linux it crashes saying it can’t find SDL2.dll. The game runs with no issues on Linux if I don’t call this method. The same behavior occurs when running it with Mono and with a native Linux executable created via mkbundle.

libSDL2-2.0.so.0 and SDL2.dll are in the x86 and x64 folders, which are in a lib folder directly outside the game executable.

I don’t have much experience with P/Invoke and would greatly appreciate any insight into why SDL2 has no issues loading everything from MonoGame but fails in my game code. Thanks in advance!

MonoGame checks way more locations than just “SDL2” for the library: https://github.com/MonoGame/MonoGame/blob/develop/MonoGame.Framework/Platform/SDL/SDL2.cs#L16

You can either copy over that resolver method and use it with FuncLoader, or you can just write few lines of code for save folder resolution per current operating system (just replace Pong with your games name):

// Windows

_saveLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Pong");

// Linux

var localShare = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
if (string.isNullOrEmpty(localShare))
{
    localShare = Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".local/share");
}
_saveLocation = Path.Combine(localShare, "Pong");
1 Like

I ended up going with Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) for all platforms. I looked at the Mono source code, and it already handles reading the environment variables for Linux to determine the correct path; less work on my end! Thanks a bunch!

Oh, they fixed it, be careful that you bundle your game with new enough version of mono then or alternatively use .NET Core when distributing on Unix platforms (before it did not work properly).