Search code examples
c#macosdllsdl-2dylib

SDL2-CS automatically trying to find libSDL2.dll instead of libSDL2.dylib on an M2 Mac


so I have finally managed to get Rider to not give errors when doing: using SDL2. I did this by not installing SDL2-CS but instead SDL2-CS.NetCore because I am using .NET 8 .

The following code is the code I am running to get the following issues:

using System;
using SDL2;

class Program
{
    static void Main()
    {
        
        // Initialize SDL with only controller and joystick support
        if (SDL.SDL_Init(SDL.SDL_INIT_GAMECONTROLLER | SDL.SDL_INIT_JOYSTICK) < 0)
        {
            Console.WriteLine("SDL could not initialize! SDL_Error: " + SDL.SDL_GetError());
            return;
        }

        Console.WriteLine("SDL initialized successfully for controller input!");

        // Cleanup SDL resources
        SDL.SDL_Quit();
    }
}

When I run this, I get the following error: System.DllNotFoundException: Unable to load shared library 'SDL2.dll' or one of its dependencies

In my Environment Variables I have: DYLD_LIBRARY_PATH=/opt/homebrew/lib:$DYLD_LIBRARY_PATH and further down in the error it says: tried: '/opt/homebrew/lib/libSDL2.dll' (no such file) Which is the correct directory, just the incorrect file (It should be libSDL2.dylib).

How do I make it look for dylib file if on a Mac and dll if on Windows? As this script should work with both Mac and Windows.


Solution

  • Ok! I finally found the answer!

    Head over to: https://github.com/flibitijibibo/SDL2-CS/tree/master

    and clone it (git clone https://github.com/flibitijibibo/SDL2-CS.git) OR download it and unzip it if necessary.

    Add a new Folder in your project directory and name it something like SDL2, note that the SDL2-CS Library is no longer needed. Then in the SDL2 folder copy the file src/SDL2.cs which is found in the git repo. It should look like this:

    SDL2 Folder example

    Then open it and change the private const string nativeLibName = "SDL2"; variable if needed but for me no change was needed, it said there were hundreds of errors at the start but this was fixed by adding <AllowUnsafeBlocks>true</AllowUnsafeBlocks> to your .csproj .

    Make sure you installed the SDL2 original library meant for C++, and copy the dylib file to your directory (This is optional I just did it to help when publishing for production). In your environment variables, link the dylib file as shown: DYLD_LIBRARY_PATH=PATH_TO_DYLIB_FILE_EXCLUDING_FILE_NAME$DYLD_LIBRARY_PATH

    Obviously replace PATH_TO_DYLIB_FILE_EXCLUDING_FILE_NAME with the actual path. Then run the code and it should work.