VB.NET Dllimport相關(guān)特點(diǎn)分析
VB.NET編程語(yǔ)言為廣大開(kāi)發(fā)人員帶來(lái)了非常大的好處。我們今天就可以通過(guò)VB.NET Dllimport特點(diǎn)的介紹來(lái)進(jìn)一步加深對(duì)這款語(yǔ)言特點(diǎn)的認(rèn)知。我們可以使用Declare語(yǔ)句調(diào)用外部DLL中的過(guò)程。但VB.NET給我們提供了另外一種更加先進(jìn)的----- Dllimport特性。
如:
- Imports System.Runtime.InteropServices
- < DllImport("user32")> _
- Function Findwindow()Function
Findwindow(ByVal lpClassName As
String, ByVal lpWindowName As
String) As Integer- End Function
- < DllImport("user32")> _
- Function MoveWindow()Function
MoveWindow(ByVal hWnd As String,
ByVal x As Integer, ByVal y As
Integer, ByVal nWidth As Integer,
ByVal nHeight As Integer, ByVal
bRepaint As Integer) As Integer- End Function
- Sub Test()Sub Test()
- Dim hWnd As Integer =
Findwindow(Nothing,
"Untitled-Nodepad")- If hWnd < > 0 Then MoveWindow
(hWnd, 0, 0, 600, 300, 1)- End Sub
這樣就可以不任何代碼實(shí)現(xiàn)便可以調(diào)用外部的Dll,即使我們改變方法名為FindwindowA,也可以順利的實(shí)現(xiàn)調(diào)用,因?yàn)槭褂肈llimport特性編譯器可以自動(dòng)追蹤實(shí)際的過(guò)程以及方法! #t#
另外,VB.NET Dllimport特性海支持幾種可選的參數(shù),來(lái)精確定義調(diào)用外部過(guò)程的方式,以及外部過(guò)程的返回值方式.
CharSet 參數(shù):用于說(shuō)明字符串傳遞給外部過(guò)程的方式,可以是CharSet.Ansi(默認(rèn)),CharSet.Unicode.CharSet.Auto.
ExactSpelling參數(shù):用于指定方法名是否和DLL中的名稱完全一致,默認(rèn)值為True.
EntryPoint參數(shù):用于指定DLL中的實(shí)際函數(shù)名稱.
CallingConvention參數(shù):為入口點(diǎn)指定調(diào)用的約定,值有WinApi(默認(rèn) 值),CDecl,FastCallStdCall和ThisCall.
SetLastError參數(shù):判斷被調(diào)用函數(shù)是否設(shè)置了最近一次Win32錯(cuò)誤代碼,如果設(shè)置為True 則可以通過(guò)Err.LastDllError方法或Marshal.GetLastWin32Error方法 讀取這些代碼.
PreServeSig參數(shù):為一個(gè)Boolean值,如果為True ,則將告訴編譯器,方法不應(yīng)被轉(zhuǎn)換為一 個(gè)返回HRESULT值函數(shù).
下面使用VB.NET Dllimport特性來(lái)調(diào)用myFunction.dll中的名為friend(friend為vb保留名稱)的方法.Dllimport特性帶有Unicode字符串,并影響Win32錯(cuò)誤代碼:
- < DllImport("myFunction.dll",
EntryPoint:="Friend", CharSet
CharSet:=CharSet.Unicode,
SetLastError:=True)> _- Function MakeFriends(ByVal sl
As String, ByVal s2 As String)
As Integer- End Function
VB.NET Dllimport的特性就為大家介紹到這里。