Advertisement
Naohiro19

DllLoader Class for VB.NET

Jun 24th, 2023
1,911
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.98 KB | None | 0 0
  1. Imports System
  2. Imports System.Runtime.InteropServices
  3.  
  4. Public Class DllLoader(Of T)
  5.     Implements IDisposable
  6.  
  7.     Private _dllHandle As IntPtr
  8.     Private _disposed As Boolean = False
  9.  
  10.     Public Property [Function] As T
  11.  
  12.     Public Sub New(dllPath As String, functionName As String)
  13.         _dllHandle = LoadLibrary(dllPath)
  14.         If _dllHandle = IntPtr.Zero Then
  15.             Throw New Exception("Failed to load DLL: " & dllPath)
  16.         End If
  17.  
  18.         Dim functionPtr As IntPtr = GetProcAddress(_dllHandle, functionName)
  19.         If functionPtr = IntPtr.Zero Then
  20.             Throw New Exception("Failed to find function: " & functionName)
  21.         End If
  22.  
  23.         [Function] = Marshal.GetDelegateForFunctionPointer(Of T)(functionPtr)
  24.     End Sub
  25.  
  26.     Protected Overrides Sub Finalize()
  27.         Dispose(False)
  28.         MyBase.Finalize()
  29.     End Sub
  30.  
  31.     Public Sub Dispose() Implements IDisposable.Dispose
  32.         Dispose(True)
  33.         GC.SuppressFinalize(Me)
  34.     End Sub
  35.  
  36.     Protected Overridable Sub Dispose(disposing As Boolean)
  37.         If Not _disposed Then
  38.             If disposing Then
  39.                 ' マネージドリソースの解放
  40.             End If
  41.  
  42.             ' アンマネージドリソースの解放
  43.             If _dllHandle <> IntPtr.Zero Then
  44.                 FreeLibrary(_dllHandle)
  45.                 _dllHandle = IntPtr.Zero
  46.             End If
  47.  
  48.             _disposed = True
  49.         End If
  50.     End Sub
  51.  
  52.     <DllImport("kernel32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)>
  53.     Private Shared Function LoadLibrary(lpFileName As String) As IntPtr
  54.     End Function
  55.  
  56.     <DllImport("kernel32.dll", CharSet:=CharSet.Ansi, SetLastError:=True)>
  57.     Private Shared Function GetProcAddress(hModule As IntPtr, lpProcName As String) As IntPtr
  58.     End Function
  59.  
  60.     <DllImport("kernel32.dll", SetLastError:=True)>
  61.     Private Shared Function FreeLibrary(hModule As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
  62.     End Function
  63. End Class
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement