M2 Mac下SDL2-CS.NetCore误找libSDL2.dll,求跨平台适配方案
解决SDL2-CS.NetCore跨平台动态库加载问题(.NET 8)
针对M2 Mac上运行SDL2初始化代码时出现的System.DllNotFoundException(程序错误查找libSDL2.dll而非libSDL2.dylib),可以通过动态指定平台对应的库文件名实现跨平台适配,以下是具体实现方案:
核心思路
利用.NET的NativeLibrary.SetDllImportResolver方法,根据当前运行的操作系统,动态替换SDL2的库文件名:
- Windows平台:使用
SDL2.dll - macOS平台:使用
libSDL2.dylib - Linux平台:使用
libSDL2.so(可选适配)
代码实现
在程序启动入口(如Program.cs的Main方法最开头)添加以下代码:
using System.Runtime.InteropServices; using SDL2; // 为SDL2所在程序集设置动态库加载解析器 NativeLibrary.SetDllImportResolver(typeof(SDL).Assembly, (libraryName, assembly, searchPath) => { string targetLibrary = libraryName; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { targetLibrary = "libSDL2.dylib"; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { targetLibrary = "libSDL2.so"; } // Windows平台保持原名称,无需修改 return NativeLibrary.Load(targetLibrary, assembly, DllImportSearchPath.SafeDirectories); }); // 后续正常调用SDL初始化逻辑 SDL.SDL_Init(SDL.SDL_INIT_VIDEO);
注意事项
- 平台库安装:确保对应平台已安装SDL2库:
- Windows:将
SDL2.dll放置在程序输出目录或系统全局路径中 - macOS:通过Homebrew安装
SDL2后,libSDL2.dylib默认在/opt/homebrew/lib,系统会自动识别 - Linux:通过包管理器安装
libsdl2-dev(如apt install libsdl2-dev)
- Windows:将
- 发布打包:若需打包发布程序,需将对应平台的SDL2库文件一同打包分发。
内容的提问来源于stack exchange,提问作者robinb
相关产品推荐
相关产品推荐

