|
| 1 | +using System; |
| 2 | +using System.Collections; |
| 3 | +using System.IO; |
| 4 | +using System.Linq; |
| 5 | +using System.Reflection; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | +using System.Xml.Linq; |
| 8 | + |
| 9 | +public static class DllMap |
| 10 | +{ |
| 11 | + // Register a call-back for native library resolution. |
| 12 | + public static void Register(Assembly assembly) |
| 13 | + { |
| 14 | + NativeLibrary.SetDllImportResolver(assembly, MapAndLoad); |
| 15 | + } |
| 16 | + |
| 17 | + // The callback: which loads the mapped libray in place of the original |
| 18 | + private static IntPtr MapAndLoad(string libraryName, Assembly assembly, DllImportSearchPath? dllImportSearchPath) |
| 19 | + { |
| 20 | + string mappedName = null; |
| 21 | + mappedName = MapLibraryName(assembly.Location, libraryName, out mappedName) ? mappedName : libraryName; |
| 22 | + return NativeLibrary.Load(mappedName, assembly, dllImportSearchPath); |
| 23 | + } |
| 24 | + |
| 25 | + // Parse the assembly.xml file, and map the old name to the new name of a library. |
| 26 | + private static bool MapLibraryName(string assemblyLocation, string originalLibName, out string mappedLibName) |
| 27 | + { |
| 28 | + string xmlPath = Path.Combine(Path.GetDirectoryName(assemblyLocation), |
| 29 | + Path.GetFileNameWithoutExtension(assemblyLocation) + ".xml"); |
| 30 | + mappedLibName = null; |
| 31 | + |
| 32 | + if (!File.Exists(xmlPath)) |
| 33 | + return false; |
| 34 | + |
| 35 | + XElement root = XElement.Load(xmlPath); |
| 36 | + var map = |
| 37 | + (from el in root.Elements("dllmap") |
| 38 | + where (string)el.Attribute("dll") == originalLibName |
| 39 | + select el).SingleOrDefault(); |
| 40 | + |
| 41 | + if (map != null) |
| 42 | + mappedLibName = map.Attribute("target").Value; |
| 43 | + |
| 44 | + return (mappedLibName != null); |
| 45 | + } |
| 46 | +} |
0 commit comments