Sdl2.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using NativeLibraryLoader;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. namespace Veldrid.Sdl2
  6. {
  7. public static unsafe partial class Sdl2Native
  8. {
  9. private static readonly NativeLibraryLoader.NativeLoader s_sdl2Lib = LoadSdl2();
  10. private static NativeLoader LoadSdl2()
  11. {
  12. string[] names;
  13. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  14. {
  15. names = new[] { "SDL2.dll" };
  16. }
  17. else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
  18. {
  19. names = new[]
  20. {
  21. "libSDL2-2.0.so",
  22. "libSDL2-2.0.so.0",
  23. "libSDL2-2.0.so.1",
  24. };
  25. }
  26. else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  27. {
  28. names = new[]
  29. {
  30. "libsdl2.dylib"
  31. };
  32. }
  33. else
  34. {
  35. Debug.WriteLine("Unknown SDL platform. Attempting to load \"SDL2\"");
  36. names = new[] { "SDL2.dll" };
  37. }
  38. NativeLoader lib = new NativeLoader("sdl2");
  39. return lib;
  40. }
  41. /// <summary>
  42. /// Loads an SDL2 function by the given name.
  43. /// </summary>
  44. /// <typeparam name="T">The delegate type of the function to load.</typeparam>
  45. /// <param name="name">The name of the exported native function.</param>
  46. /// <returns>A delegate which can be used to invoke the native function.</returns>
  47. /// <exception cref="System.InvalidOperationException">Thrown when no function with the given name is exported by SDL2.
  48. /// </exception>
  49. public static T LoadFunction<T>(string name)
  50. {
  51. try
  52. {
  53. return s_sdl2Lib.LoadFunction<T>(name);
  54. }
  55. catch
  56. {
  57. Debug.WriteLine(
  58. $"Unable to load SDL2 function \"{name}\". " +
  59. $"Attempting to call this function will cause an exception to be thrown.");
  60. return default(T);
  61. }
  62. }
  63. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  64. private delegate byte* SDL_GetError_t();
  65. private static SDL_GetError_t s_sdl_getError = LoadFunction<SDL_GetError_t>("SDL_GetError");
  66. public static byte* SDL_GetError() => s_sdl_getError();
  67. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  68. private delegate void SDL_ClearError_t();
  69. private static SDL_ClearError_t s_sdl_clearError = LoadFunction<SDL_ClearError_t>("SDL_ClearError");
  70. public static byte* SDL_ClearError() { s_sdl_clearError(); return null; }
  71. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  72. private delegate void SDL_free_t(void* ptr);
  73. private static SDL_free_t s_sdl_free = LoadFunction<SDL_free_t>("SDL_free");
  74. public static void SDL_free(void* ptr) { s_sdl_free(ptr); }
  75. }
  76. }