VB.NET Dllimport特性内容概述

VB.NET的出现,为我们带来了很多新颖的特性。在很大程度上增加了开发人员的编程效率。在这里我们就一起来体验它的一些特性优点。我们可以使用Declare语句调用外部DLL中的过程。但VB.NET给我们提供了另外一种更加先进的----- VB.NET Dllimport特性。

如:

 

 
 
 
  1. Imports System.Runtime.
    InteropServices  
  2. < DllImport("user32")> _  
  3. Function Findwindow(ByVal 
    lpClassName As String, ByVal 
    lpWindowName As String) As Integer  
  4. End Function  
  5. < DllImport("user32")> _  
  6. 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  
  7. End Function  
  8. Sub Test()  
  9. Dim hWnd As Integer = Findwindow
    (Nothing, "Untitled-Nodepad")  
  10. If hWnd < > 0 Then MoveWindow
    (hWnd, 0, 0, 600, 300, 1)  
  11. End Sub 

 

这样就可以不任何代码实现便可以调用外部的Dll,即使我们改变方法名为FindwindowA,也可以顺利的实现调用,因为使用Dllimport特性编译器可以自动追踪实际的过程以及方法!#t#

另外,VB.NET Dllimport特性支持几种可选的参数,来精确定义调用外部过程的方式,以及外部过程的返回值方式.

CharSet 参数:用于说明字符串传递给外部过程的方式,可以是CharSet.Ansi(默认),CharSet.Unicode.CharSet.Auto.

ExactSpelling参数:用于指定方法名是否和DLL中的名称完全一致,默认值为True.

EntryPoint参数:用于指定DLL中的实际函数名称.

CallingConvention参数:为入口点指定调用的约定,值有WinApi(默认值),CDecl,FastCallStdCall和ThisCall.

SetLastError参数:判断被调用函数是否设置了最近一次Win32错误代码,如果设置为True则可以通过Err.LastDllError方法或Marshal.GetLastWin32Error方法读取这些代码.

PreServeSig参数:为一个Boolean值,如果为True ,则将告诉编译器,方法不应被转换为一个返回HRESULT值函数.

下面使用VB.NET Dllimport特性来调用myFunction.dll中的名为friend(friend为VB保留名称)的方法.Dllimport特性带有Unicode字符串,并影响Win32错误代码:

 

 
 
 
  1. < DllImport("myFunction.dll", 
    EntryPoint:="Friend"CharSet
    CharSet:=CharSet.Unicode, 
    SetLastError:=True)> _  
  2. Function MakeFriends(ByVal sl 
    As String, ByVal s2 As String) 
    As Integer  
  3. End Function 

 

THE END