Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports System
- Imports System.Runtime.InteropServices
- Public Class DllLoader(Of T)
- Implements IDisposable
- Private _dllHandle As IntPtr
- Private _disposed As Boolean = False
- Public Property [Function] As T
- Public Sub New(dllPath As String, functionName As String)
- _dllHandle = LoadLibrary(dllPath)
- If _dllHandle = IntPtr.Zero Then
- Throw New Exception("Failed to load DLL: " & dllPath)
- End If
- Dim functionPtr As IntPtr = GetProcAddress(_dllHandle, functionName)
- If functionPtr = IntPtr.Zero Then
- Throw New Exception("Failed to find function: " & functionName)
- End If
- [Function] = Marshal.GetDelegateForFunctionPointer(Of T)(functionPtr)
- End Sub
- Protected Overrides Sub Finalize()
- Dispose(False)
- MyBase.Finalize()
- End Sub
- Public Sub Dispose() Implements IDisposable.Dispose
- Dispose(True)
- GC.SuppressFinalize(Me)
- End Sub
- Protected Overridable Sub Dispose(disposing As Boolean)
- If Not _disposed Then
- If disposing Then
- ' マネージドリソースの解放
- End If
- ' アンマネージドリソースの解放
- If _dllHandle <> IntPtr.Zero Then
- FreeLibrary(_dllHandle)
- _dllHandle = IntPtr.Zero
- End If
- _disposed = True
- End If
- End Sub
- <DllImport("kernel32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)>
- Private Shared Function LoadLibrary(lpFileName As String) As IntPtr
- End Function
- <DllImport("kernel32.dll", CharSet:=CharSet.Ansi, SetLastError:=True)>
- Private Shared Function GetProcAddress(hModule As IntPtr, lpProcName As String) As IntPtr
- End Function
- <DllImport("kernel32.dll", SetLastError:=True)>
- Private Shared Function FreeLibrary(hModule As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
- End Function
- End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement