Hossam Fares
Hossam Fares

Reputation: 33

How to use SDL2 with .NET MAUI

I am trying to use SDL2 with .NET MAUI.

I have tried to build the native libraries using the androidbuildlibs.sh at the buildscripts directory. it generated libSDL.so for different architectures. and then I added them to libs/ directory in the project and set there build action to AndroidNativeLibrary. when I try to Initialize SDL using:

[DllImport("libSDL2.so", CallingConvention = CallingConvention.Cdecl)]
public static extern int SDL_Init(uint flags);

the SDL_Init method returns -1.

I thought I should Initialize it somewhere in the MainActivity. so, I built the java library that contains SDLActivity to .jar file and I made a binding project to it. then I tried to make the MainActivity inherit from SDLActivity instead of MauiAppCompatActivity. and I overrided the LoadLibraries method like so:

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : SDLActivity
{
    public override void LoadLibraries()
    {
        base.LoadLibraries();
        SDL2Helper.InitSDL();
    }
}

Now I get an error indicating that the libmain.so not found.

Upvotes: 3

Views: 121

Answers (1)

signum
signum

Reputation: 56

I'm also trying to get SDL2 working with Xamarin and MAUI.

I also created a bindings project with a .jar file and added the libraries to the lib folder.

I don't want to inherit directly from SDLActivity so I'm trying to initialize SDL manually.

This code is based on Qt issue and android-project source code from libsdl repository:

https://github.com/libsdl-org/SDL/issues/5356

https://github.com/libsdl-org/SDL/tree/SDL2/android-project

Here's an example of how I got SDL working on MAUI:

 public class MainActivity : MauiAppCompatActivity
 {
     protected override void OnCreate(Bundle? savedInstanceState)
     {
         base.OnCreate(savedInstanceState);
         InitSdl();
     }

     protected override void OnDestroy()
     {
         base.OnDestroy();
         CloseSdl();
     }

     private void InitSdl()
     {
         // SDL is a class from android-project (.jar file)
         SDL.LoadLibrary("SDL2", this);
         SDL.SetupJNI();
         SDL.Initialize();
         SDL.Context = this;
         SdlBinding.SDL_SetMainReady();
         var initCode = SdlBinding.SDL_Init(SdlBinding.SDL_INIT_AUDIO);
         if (initCode != 0)
             throw new Exception("SDL initialization failed");
     }

     private void CloseSdl()
     {
         SdlBinding.SDL_Quit();
         if (SDL.Context == this)
         {
             SDL.Context = null;
         }
     }
 }

Upvotes: 1

Related Questions