-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathWindowsLibraryLoader.cs
388 lines (339 loc) · 14.6 KB
/
WindowsLibraryLoader.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
#pragma warning disable 1591
namespace OpenCvSharp.Internal
{
/// <summary>
/// Handles loading embedded dlls into memory, based on http://stackoverflow.com/questions/666799/embedding-unmanaged-dll-into-a-managed-c-sharp-dll.
/// </summary>
/// <remarks>This code is based on https://github.com/charlesw/tesseract </remarks>
public sealed class WindowsLibraryLoader
{
public static WindowsLibraryLoader Instance { get; } = new();
/// <summary>
/// The default base directory name to copy the assemblies too.
/// </summary>
private const string ProcessorArchitecture = "PROCESSOR_ARCHITECTURE";
private const string DllFileExtension = ".dll";
private const string DllDirectory = "dll";
private readonly List<string> loadedAssemblies = new();
/// <summary>
/// Map processor
/// </summary>
private readonly Dictionary<string, string> processorArchitecturePlatforms =
new (StringComparer.OrdinalIgnoreCase)
{
{"x86", "x86"},
{"AMD64", "x64"},
{"IA64", "Itanium"},
{"ARM", "WinCE"}
};
/// <summary>
/// Used as a sanity check for the returned processor architecture to double check the returned value.
/// </summary>
private readonly Dictionary<string, int> processorArchitectureAddressWidthPlatforms =
new(StringComparer.OrdinalIgnoreCase)
{
{"x86", 4},
{"AMD64", 8},
{"IA64", 8},
{"ARM", 4}
};
/// <summary>
/// Additional user-defined DLL paths
/// </summary>
#pragma warning disable CA1002 // Do not expose generic lists
public List<string> AdditionalPaths { get; }
#pragma warning restore CA1002
private readonly object syncLock = new();
/// <summary>
/// constructor
/// </summary>
private WindowsLibraryLoader()
{
AdditionalPaths = new List<string>();
}
/// <summary>
///
/// </summary>
/// <param name="dllName"></param>
/// <returns></returns>
public bool IsLibraryLoaded(string dllName)
{
lock (syncLock)
{
return loadedAssemblies.Contains(dllName);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static bool IsCurrentPlatformSupported()
{
#if NET461
return Environment.OSVersion.Platform == PlatformID.Win32NT ||
Environment.OSVersion.Platform == PlatformID.Win32Windows;
#else
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#endif
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static bool IsDotNetCore()
{
#if NET461
return false;
#else
// https://github.com/dotnet/corefx/blob/v2.1-preview1/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.cs
return RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.Ordinal);
#endif
}
/// <summary>
///
/// </summary>
/// <param name="dllName"></param>
/// <param name="additionalPaths"></param>
public void LoadLibrary(string dllName, IEnumerable<string>? additionalPaths = null)
{
// Windows only
if (!IsCurrentPlatformSupported())
return;
var additionalPathsArray = additionalPaths?.ToArray() ?? Array.Empty<string>();
// In .NET Core, process only when additional paths are specified.
if (IsDotNetCore() && additionalPathsArray.Length == 0)
return;
try
{
lock (syncLock)
{
if (loadedAssemblies.Contains(dllName))
{
return;
}
var processArch = GetProcessArchitecture();
IntPtr dllHandle;
// Try loading from user-defined paths
foreach (var path in additionalPathsArray)
{
// baseDirectory = Path.GetFullPath(path);
dllHandle = LoadLibraryRaw(dllName, path);
if (dllHandle != IntPtr.Zero) return;
}
// Try loading from executing assembly domain
#if DOTNET_FRAMEWORK
var executingAssembly = Assembly.GetExecutingAssembly();
#else
var executingAssembly = GetType().GetTypeInfo().Assembly;
#endif
var baseDirectory = Path.GetDirectoryName(executingAssembly.Location) ?? "";
dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch);
if (dllHandle != IntPtr.Zero) return;
// Fallback to current app domain
// TODO
#if DOTNET_FRAMEWORK
baseDirectory = Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory);
dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch);
if (dllHandle != IntPtr.Zero) return;
#endif
// Gets the pathname of the base directory that the assembly resolver uses to probe for assemblies.
// https://github.com/dotnet/corefx/issues/2221
#if !NET40
baseDirectory = AppContext.BaseDirectory;
dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch);
if (dllHandle != IntPtr.Zero) return;
#endif
// Finally try the working directory
baseDirectory = Path.GetFullPath(Directory.GetCurrentDirectory());
dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch);
if (dllHandle != IntPtr.Zero) return;
// ASP.NET hack, requires an active context
#if DOTNET_FRAMEWORK
if (System.Web.HttpContext.Current != null)
{
var server = System.Web.HttpContext.Current.Server;
baseDirectory = Path.GetFullPath(server.MapPath("bin"));
dllHandle = LoadLibraryInternal(dllName, baseDirectory, processArch);
if (dllHandle != IntPtr.Zero) return;
}
#endif
var errorMessage = new StringBuilder();
errorMessage.Append($"Failed to find dll \"{dllName}\", for processor architecture {processArch.Architecture}.");
if (processArch.HasWarnings)
{
// include process detection warnings
errorMessage.AppendLine().Append($"Warnings: ").AppendLine().Append("{processArch.WarningText()}");
}
throw new OpenCvSharpException(errorMessage.ToString());
}
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception e)
{
Debug.WriteLine(e);
}
#pragma warning restore CA1031 // Do not catch general exception types
}
/// <summary>
/// Get's the current process architecture while keeping track of any assumptions or possible errors.
/// </summary>
/// <returns></returns>
private ProcessArchitectureInfo GetProcessArchitecture()
{
// BUGBUG: Will this always be reliable?
var processArchitecture = Environment.GetEnvironmentVariable(ProcessorArchitecture);
var processInfo = new ProcessArchitectureInfo();
if (!string.IsNullOrEmpty(processArchitecture))
{
// Sanity check
processInfo.Architecture = processArchitecture!;
}
else
{
processInfo.AddWarning("Failed to detect processor architecture, falling back to x86.");
processInfo.Architecture = (IntPtr.Size == 8) ? "x64" : "x86";
}
var addressWidth = processorArchitectureAddressWidthPlatforms[processInfo.Architecture];
if (addressWidth != IntPtr.Size)
{
if (string.Equals(processInfo.Architecture, "AMD64", StringComparison.OrdinalIgnoreCase) && IntPtr.Size == 4)
{
// fall back to x86 if detected x64 but has an address width of 32 bits.
processInfo.Architecture = "x86";
processInfo.AddWarning("Expected the detected processing architecture of {0} to have an address width of {1} Bytes but was {2} Bytes, falling back to x86.", processInfo.Architecture, addressWidth, IntPtr.Size);
}
else
{
// no fallback possible
processInfo.AddWarning("Expected the detected processing architecture of {0} to have an address width of {1} Bytes but was {2} Bytes.", processInfo.Architecture, addressWidth, IntPtr.Size);
}
}
return processInfo;
}
private IntPtr LoadLibraryInternal(string dllName, string baseDirectory, ProcessArchitectureInfo processArchInfo)
{
//IntPtr libraryHandle = IntPtr.Zero;
var platformName = GetPlatformName(processArchInfo.Architecture) ?? "";
var expectedDllDirectory = Path.Combine(
Path.Combine(baseDirectory, DllDirectory), platformName);
//var fileName = FixUpDllFileName(Path.Combine(expectedDllDirectory, dllName));
return LoadLibraryRaw(dllName, expectedDllDirectory);
}
private IntPtr LoadLibraryRaw(string dllName, string baseDirectory)
{
var libraryHandle = IntPtr.Zero;
var fileName = FixUpDllFileName(Path.Combine(baseDirectory, dllName));
#if WINRT && false
// MP! Note: This is a hack, needs refinement. We don't need to carry payload of both binaries for WinRT because the appx is platform specific.
ProcessArchitectureInfo processInfo = GetProcessArchitecture();
string cpu = "x86";
if (processInfo.Architecture == "AMD64")
cpu = "x64";
string dllpath = baseDirectory.Replace($"dll\\{cpu}", "");
fileName = $"{dllpath}{dllName}.dll";
// Show where we're trying to load the file from
Debug.WriteLine($"Trying to load native library \"{fileName}\"...");
#endif
if (File.Exists(fileName))
{
// Attempt to load dll
try
{
libraryHandle = Win32Api.LoadLibrary(fileName);
if (libraryHandle != IntPtr.Zero)
{
// library has been loaded
Debug.WriteLine($"Successfully loaded native library \"{fileName}\".");
loadedAssemblies.Add(dllName);
}
else
{
Debug.WriteLine($"Failed to load native library \"{fileName}\".\r\nCheck windows event log.");
}
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception e)
{
// ReSharper disable once RedundantAssignment
var lastError = Marshal.GetLastWin32Error();
Debug.WriteLine(
$"Failed to load native library \"{fileName}\".\r\nLast Error:{lastError}\r\nCheck inner exception and\\or windows event log.\r\nInner Exception: {e}");
}
#pragma warning restore CA1031 // Do not catch general exception types
}
else
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture,
"The native library \"{0}\" does not exist.",
fileName));
}
return libraryHandle;
}
/// <summary>
/// Determines if the dynamic link library file name requires a suffix
/// and adds it if necessary.
/// </summary>
private static string FixUpDllFileName(string fileName)
{
if (!string.IsNullOrEmpty(fileName))
{
#if DOTNET_FRAMEWORK
var platformId = Environment.OSVersion.Platform;
if ((platformId == PlatformID.Win32S) ||
(platformId == PlatformID.Win32Windows) ||
(platformId == PlatformID.Win32NT) ||
(platformId == PlatformID.WinCE))
#else
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
#endif
{
if (!fileName.EndsWith(DllFileExtension,
StringComparison.OrdinalIgnoreCase))
{
return fileName + DllFileExtension;
}
}
}
return fileName;
}
/// <summary>
/// Given the processor architecture, returns the name of the platform.
/// </summary>
private string? GetPlatformName(string processorArchitecture)
{
if (string.IsNullOrEmpty(processorArchitecture))
return null;
if (processorArchitecturePlatforms.TryGetValue(processorArchitecture, out var platformName))
return platformName;
return null;
}
private class ProcessArchitectureInfo
{
public string Architecture { get; set; }
private List<string> Warnings { get; }
public ProcessArchitectureInfo()
{
Architecture = "";
Warnings = new List<string>();
}
public bool HasWarnings => Warnings.Count > 0;
public void AddWarning(string format, params object[] args)
{
Warnings.Add(string.Format(CultureInfo.InvariantCulture, format, args));
}
public string WarningText()
{
return string.Join("\r\n", Warnings.ToArray());
}
}
}
}