如何在VB.NET中引用Dll

在VB.NET中通常可以用'加入參考'的方式來引用DLL
也可以用宣告API的方式,這裡我用的是另一種方式
1.需要用到一些函式 LoadLibrary , GetProcAddress , GetModuleHandle , FreeLibrary
Public Declare Function GetProcAddress Lib "kernel32" _
(ByVal hModule As Integer, ByVal lpProcName As String) As Integer
Public Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" _
(ByVal lpProcName As String) As Integer
Public Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" _
(ByVal lpModuleName As String) As Integer
Public Declare Function FreeLibrary Lib "kernel32" Alias "FreeLibrary" _
(ByVal hLibModule As Integer) As Integer

2.加入System.Runtime.InteropServices參考
Imports System.Runtime.InteropServices
3.宣告委派,依據DLL的函式,例如
Public Delegate Function DllFunction _
(ByVal Parameter As Integer) As Integer

4.建立函式,例如
Public Function FDllFunction _
(ByVal Parameter As Integer) As Integer
If hDEV = 0 Then Return -1
Dim v As Integer = GetProcAddress(hDEV, "DllFunction")
Dim a As DllFunction = _
CType(Marshal.GetDelegateForFunctionPointer(New IntPtr(v), _
GetType(DllFunction)), DllFunction)
If IsNothing(a) = False Then FDllFunction = a.Invoke(Parameter)
End Function

5.在使用DLL函式前,要先呼叫 Loadlibary
結束程式也要呼叫 FreeLibary

留言

熱門文章