-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathNativeLibraryHelper.cs
67 lines (59 loc) · 2.25 KB
/
NativeLibraryHelper.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
// Copyright 2021 Ayoub Kaanich <[email protected]>
// SPDX-License-Identifier: MIT
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace SharpPcap.LibPcap
{
class NativeLibraryHelper
{
public delegate IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath);
private static readonly Type NativeLibraryType = typeof(DllImportSearchPath).Assembly
.GetType("System.Runtime.InteropServices.NativeLibrary");
public static void SetDllImportResolver(Assembly assembly, DllImportResolver resolver)
{
if (NativeLibraryType == null)
{
return;
}
#if NET6_0_OR_GREATER
NativeLibrary.SetDllImportResolver(assembly, (lib, asm, path) => resolver(lib, asm, path));
#else
var dllImportResolverType = typeof(DllImportSearchPath).Assembly
.GetType("System.Runtime.InteropServices.DllImportResolver");
var setDllImportResolverMethod = NativeLibraryType
.GetMethod(
"SetDllImportResolver",
BindingFlags.Public | BindingFlags.Static,
null,
new[] { typeof(Assembly), dllImportResolverType },
null
);
setDllImportResolverMethod.Invoke(null, new object[] {
assembly,
Delegate.CreateDelegate(dllImportResolverType, resolver, "Invoke")
});
#endif
}
public static bool TryLoad(string libraryPath, out IntPtr handle)
{
var tryLoadMethod = NativeLibraryType
?.GetMethod(
"TryLoad",
BindingFlags.Public | BindingFlags.Static,
null,
new[] { typeof(string), typeof(IntPtr).MakeByRefType() },
null
);
if (tryLoadMethod == null)
{
handle = IntPtr.Zero;
return false;
}
var args = new object[] { libraryPath, IntPtr.Zero };
var res = (bool)tryLoadMethod.Invoke(null, args);
handle = (IntPtr)args[1];
return res;
}
}
}