2 using System.Reflection;
\r
3 using System.Runtime.InteropServices;
\r
5 namespace NaGet.InteropServices
\r
8 /// DLLへの動的アクセスを行うクラス
\r
10 public class DllAccess : IDisposable
\r
14 [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
\r
15 private extern static IntPtr LoadLibrary(string lpFileName);
\r
17 [DllImport("kernel32.dll")]
\r
18 private extern static bool FreeLibrary(IntPtr hModule);
\r
20 [DllImport("kernel32.dll", CharSet=CharSet.Ansi)]
\r
21 private extern static IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
\r
25 private IntPtr hModule = IntPtr.Zero;
\r
28 /// コンストラクタ。DLLを読み込む
\r
30 /// <param name="dllName">
\r
31 /// DLLの名称。直接Win32APIのLoadLibraryにわたされる
\r
33 public DllAccess(string dllName)
\r
35 hModule = LoadLibrary(dllName);
\r
36 if (hModule == IntPtr.Zero) {
\r
37 Exception innerEx = null;
\r
39 innerEx = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
\r
42 throw new DllNotFoundException("Failed to LoadLibrary " + dllName, innerEx);
\r
47 /// 関数をdelegateに変換して得る
\r
49 /// <param name="strProcName">
\r
52 /// <param name="type">
\r
53 /// 関数の型。戻り値のdelegateのタイプ
\r
56 /// delegateに変換された関数
\r
58 public Delegate GetFunction(string strProcName, Type type)
\r
60 IntPtr pFunc = GetProcAddress(hModule, strProcName);
\r
61 if (pFunc == IntPtr.Zero) {
\r
62 int result = Marshal.GetHRForLastWin32Error();
\r
63 throw Marshal.GetExceptionForHR(result);
\r
66 return Marshal.GetDelegateForFunctionPointer(pFunc, type);
\r
72 public void Dispose()
\r
74 if (hModule != IntPtr.Zero) {
\r
75 FreeLibrary(hModule);
\r
76 hModule = IntPtr.Zero;
\r