Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.InteropServices;
- public class DllLoader<T> : IDisposable
- {
- private IntPtr _dllHandle;
- private bool _disposed;
- public T Function { get; private set; }
- public DllLoader(string dllPath, string functionName)
- {
- _dllHandle = LoadLibrary(dllPath);
- if (_dllHandle == IntPtr.Zero)
- {
- throw new Exception("Failed to load DLL: " + dllPath);
- }
- IntPtr functionPtr = GetProcAddress(_dllHandle, functionName);
- if (functionPtr == IntPtr.Zero)
- {
- throw new Exception("Failed to find function: " + functionName);
- }
- Function = Marshal.GetDelegateForFunctionPointer<T>(functionPtr);
- }
- ~DllLoader()
- {
- Dispose(false);
- }
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- protected virtual void Dispose(bool disposing)
- {
- if (!_disposed)
- {
- if (disposing)
- {
- // マネージドリソースの解放
- }
- // アンマネージドリソースの解放
- if (_dllHandle != IntPtr.Zero)
- {
- FreeLibrary(_dllHandle);
- _dllHandle = IntPtr.Zero;
- }
- _disposed = true;
- }
- }
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
- private static extern IntPtr LoadLibrary(string lpFileName);
- [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
- private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
- [DllImport("kernel32.dll", SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool FreeLibrary(IntPtr hModule);
- }
Advertisement
Add Comment
Please, Sign In to add comment