Naohiro19

DllLoader Class for C#

Jun 24th, 2023
1,168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using System;
  2. using System.Runtime.InteropServices;
  3.  
  4. public class DllLoader<T> : IDisposable
  5. {
  6.     private IntPtr _dllHandle;
  7.     private bool _disposed;
  8.  
  9.     public T Function { get; private set; }
  10.  
  11.     public DllLoader(string dllPath, string functionName)
  12.     {
  13.         _dllHandle = LoadLibrary(dllPath);
  14.         if (_dllHandle == IntPtr.Zero)
  15.         {
  16.             throw new Exception("Failed to load DLL: " + dllPath);
  17.         }
  18.  
  19.         IntPtr functionPtr = GetProcAddress(_dllHandle, functionName);
  20.         if (functionPtr == IntPtr.Zero)
  21.         {
  22.             throw new Exception("Failed to find function: " + functionName);
  23.         }
  24.  
  25.         Function = Marshal.GetDelegateForFunctionPointer<T>(functionPtr);
  26.     }
  27.  
  28.     ~DllLoader()
  29.     {
  30.         Dispose(false);
  31.     }
  32.  
  33.     public void Dispose()
  34.     {
  35.         Dispose(true);
  36.         GC.SuppressFinalize(this);
  37.     }
  38.  
  39.     protected virtual void Dispose(bool disposing)
  40.     {
  41.         if (!_disposed)
  42.         {
  43.             if (disposing)
  44.             {
  45.                 // マネージドリソースの解放
  46.             }
  47.  
  48.             // アンマネージドリソースの解放
  49.             if (_dllHandle != IntPtr.Zero)
  50.             {
  51.                 FreeLibrary(_dllHandle);
  52.                 _dllHandle = IntPtr.Zero;
  53.             }
  54.  
  55.             _disposed = true;
  56.         }
  57.     }
  58.  
  59.     [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  60.     private static extern IntPtr LoadLibrary(string lpFileName);
  61.  
  62.     [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
  63.     private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
  64.  
  65.     [DllImport("kernel32.dll", SetLastError = true)]
  66.     [return: MarshalAs(UnmanagedType.Bool)]
  67.     private static extern bool FreeLibrary(IntPtr hModule);
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment