|
| 1 | +using System.Reflection; |
| 2 | +using System.Runtime.InteropServices; |
| 3 | + |
| 4 | +namespace RailReader.Core.Services; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// Registers a DllImport resolver for the "pdfium" native library. |
| 8 | +/// On Linux/macOS the NuGet package ships as libpdfium.so/.dylib in |
| 9 | +/// runtimes/{rid}/native/. .NET's default probing normally finds it |
| 10 | +/// (tries lib prefix + platform extension), but this resolver provides |
| 11 | +/// an explicit fallback to guarantee resolution on all platforms. |
| 12 | +/// |
| 13 | +/// Call <see cref="Initialize"/> once at startup, before any P/Invoke |
| 14 | +/// into PDFium (PdfOutlineExtractor, PdfTextService). |
| 15 | +/// PDFtoImage must be referenced so the native asset is deployed. |
| 16 | +/// </summary> |
| 17 | +public static class PdfiumResolver |
| 18 | +{ |
| 19 | + private static bool s_initialized; |
| 20 | + |
| 21 | + public static void Initialize() |
| 22 | + { |
| 23 | + if (s_initialized) return; |
| 24 | + s_initialized = true; |
| 25 | + |
| 26 | + NativeLibrary.SetDllImportResolver( |
| 27 | + typeof(PdfiumResolver).Assembly, |
| 28 | + ResolvePdfium); |
| 29 | + } |
| 30 | + |
| 31 | + private static IntPtr ResolvePdfium(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) |
| 32 | + { |
| 33 | + if (libraryName != "pdfium") |
| 34 | + return IntPtr.Zero; // fall back to default resolution |
| 35 | + |
| 36 | + // Try default probing first (handles most cases) |
| 37 | + if (NativeLibrary.TryLoad(libraryName, assembly, searchPath, out var handle)) |
| 38 | + return handle; |
| 39 | + |
| 40 | + // Explicit platform-specific fallback |
| 41 | + string ext, prefix; |
| 42 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| 43 | + { |
| 44 | + ext = ".dll"; |
| 45 | + prefix = ""; |
| 46 | + } |
| 47 | + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) |
| 48 | + { |
| 49 | + ext = ".dylib"; |
| 50 | + prefix = "lib"; |
| 51 | + } |
| 52 | + else |
| 53 | + { |
| 54 | + ext = ".so"; |
| 55 | + prefix = "lib"; |
| 56 | + } |
| 57 | + |
| 58 | + string libFile = $"{prefix}pdfium{ext}"; |
| 59 | + string[] candidates = |
| 60 | + [ |
| 61 | + Path.Combine(AppContext.BaseDirectory, |
| 62 | + "runtimes", RuntimeInformation.RuntimeIdentifier, "native", libFile), |
| 63 | + Path.Combine(AppContext.BaseDirectory, libFile), |
| 64 | + ]; |
| 65 | + |
| 66 | + foreach (var path in candidates) |
| 67 | + { |
| 68 | + if (File.Exists(path) && NativeLibrary.TryLoad(path, out handle)) |
| 69 | + return handle; |
| 70 | + } |
| 71 | + |
| 72 | + return IntPtr.Zero; |
| 73 | + } |
| 74 | +} |
0 commit comments