Declare StatementDeclare Statement

宣告在外部檔案中執行之程式的參考。Declares a reference to a procedure implemented in an external file.

語法Syntax

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ Overloads ] _
Declare [ charsetmodifier ] [ Sub ] name Lib "libname" _
[ Alias "aliasname" ] [ ([ parameterlist ]) ]
' -or-
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ Overloads ] _
Declare [ charsetmodifier ] [ Function ] name Lib "libname" _
[ Alias "aliasname" ] [ ([ parameterlist ]) ] [ As returntype ]

組件Parts

詞彙Term 定義Definition
attributelist 選擇性。Optional. 請參閱屬性清單See Attribute List.
accessmodifier 選擇性。Optional. 可以是下列其中一項:Can be one of the following:

- 公用- Public
- 保護- Protected
- Friend- Friend
- - Private
- 受保護的 Friend- Protected Friend
- 私用保護- Private Protected

請參閱 Access levels in Visual BasicSee Access levels in Visual Basic.
Shadows 選擇性。Optional. 請參閱ShadowsSee Shadows.
charsetmodifier 選擇性。Optional. 指定字元集和檔案搜尋資訊。Specifies character set and file search information. 可以是下列其中一項:Can be one of the following:

- Ansi (預設值)- Ansi (default)
- Unicode- Unicode
- Auto- Auto
Sub 選擇性,但 SubFunction 必須出現。Optional, but either Sub or Function must appear. 表示外部程式不會傳回值。Indicates that the external procedure does not return a value.
Function 選擇性,但 SubFunction 必須出現。Optional, but either Sub or Function must appear. 表示外部程式會傳回值。Indicates that the external procedure returns a value.
name 必要。Required. 此外部參考的名稱。Name of this external reference. 如需詳細資訊,請參閱宣告的元素名稱For more information, see Declared Element Names.
Lib 必要。Required. 引進了一個 Lib 子句,可識別包含外部程式的外部檔案(DLL 或程式碼資源)。Introduces a Lib clause, which identifies the external file (DLL or code resource) that contains an external procedure.
libname 必要。Required. 包含宣告之程式的檔案名。Name of the file that contains the declared procedure.
Alias 選擇性。Optional. 指出所宣告的程式在其檔案中無法依照 name中指定的名稱來識別。Indicates that the procedure being declared cannot be identified within its file by the name specified in name. 您會在 aliasname中指定其識別。You specify its identification in aliasname.
aliasname 如果您使用 Alias 關鍵字,則為必要。Required if you use the Alias keyword. 以兩種方式之一來識別程式的字串:String that identifies the procedure in one of two ways:

程式在其檔案中的進入點名稱,以引號括住(""The entry point name of the procedure within its file, within quotes ("")

-或--or-

數位記號(#),後面接著一個整數,指定程式在其檔案內的進入點序號A number sign (#) followed by an integer specifying the ordinal number of the procedure's entry point within its file
parameterlist 如果程式採用參數,則為必要。Required if the procedure takes parameters. 請參閱參數清單See Parameter List.
returntype 如果指定 Function,且 On``Option Strict,則為必要。Required if Function is specified and Option Strict is On. 程式所傳回值的資料類型。Data type of the value returned by the procedure.

備註Remarks

有時候您需要呼叫專案外部檔案中定義的程式(例如 DLL 或程式碼資源)。Sometimes you need to call a procedure defined in a file (such as a DLL or code resource) outside your project. 當您這麼做時,Visual Basic 編譯器無法存取正確呼叫程式所需的資訊,例如程式所在位置、識別方式、其呼叫順序和傳回類型,以及它所使用的字串字元集。When you do this, the Visual Basic compiler does not have access to the information it needs to call the procedure correctly, such as where the procedure is located, how it is identified, its calling sequence and return type, and the string character set it uses. Declare 語句會建立外部程式的參考,並提供此必要資訊。The Declare statement creates a reference to an external procedure and supplies this necessary information.

您只能在模組層級使用 DeclareYou can use Declare only at module level. 這表示外部參考的宣告內容必須是類別、結構或模組,而且不能是原始程式檔、命名空間、介面、程式或區塊。This means the declaration context for an external reference must be a class, structure, or module, and cannot be a source file, namespace, interface, procedure, or block. 如需詳細資訊,請參閱宣告內容和預設存取層級For more information, see Declaration Contexts and Default Access Levels.

外部參考預設為公用存取。External references default to Public access. 您可以使用存取修飾詞來調整其存取層級。You can adjust their access levels with the access modifiers.

規則Rules

  • 特性.Attributes. 您可以將屬性套用至外部參考。You can apply attributes to an external reference. 您套用的任何屬性只有在您的專案中才有效,而不是在外部檔案中。Any attribute you apply has effect only in your project, not in the external file.

  • 修改.Modifiers. 外部程式會隱含共用External procedures are implicitly Shared. 當您宣告外部參考時,無法使用 Shared 關鍵字,而且您無法改變其共用狀態。You cannot use the Shared keyword when declaring an external reference, and you cannot alter its shared status.

    外部程式無法參與覆寫、執行介面成員或處理事件。An external procedure cannot participate in overriding, implement interface members, or handle events. 因此,您不能在 Implements語句中使用 OverridesOverridableNotOverridableMustOverrideHandlesDeclare 關鍵字。Accordingly, you cannot use the Overrides, Overridable, NotOverridable, MustOverride, Implements, or Handles keyword in a Declare statement.

  • 外部程式名稱。External Procedure Name. 您不需要授與此外部參考與外部檔案(aliasname)中程式的進入點名稱相同的名稱(在 name中)。You do not have to give this external reference the same name (in name) as the procedure's entry-point name within its external file (aliasname). 您可以使用 Alias 子句來指定進入點名稱。You can use an Alias clause to specify the entry-point name. 如果外部程式的名稱與 Visual Basic 保留的修飾詞或變數、程式或相同範圍中的任何其他程式設計項目同名,這就很有用。This can be useful if the external procedure has the same name as a Visual Basic reserved modifier or a variable, procedure, or any other programming element in the same scope.

    注意

    大部分 Dll 中的進入點名稱都區分大小寫。Entry-point names in most DLLs are case-sensitive.

  • 外部程式編號。External Procedure Number. 或者,您可以使用 Alias 子句來指定外部檔案之匯出資料表內進入點的序號。Alternatively, you can use an Alias clause to specify the ordinal number of the entry point within the export table of the external file. 若要這麼做,您可以使用數位記號(#)開始 aliasnameTo do this, you begin aliasname with a number sign (#). 如果 Visual Basic 中不允許外部程式名稱中的任何字元,或如果外部檔案匯出程式但沒有名稱,這會很有用。This can be useful if any character in the external procedure name is not allowed in Visual Basic, or if the external file exports the procedure without a name.

資料類型規則Data Type Rules

  • 參數資料類型。Parameter Data Types. 如果 On``Option Strict,您就必須在 parameterlist中指定每個參數的資料類型。If Option Strict is On, you must specify the data type of each parameter in parameterlist. 這可以是任何資料類型,或是列舉、結構、類別或介面的名稱。This can be any data type or the name of an enumeration, structure, class, or interface. parameterlist中,您可以使用 As 子句來指定要傳遞至每個參數之引數的資料類型。Within parameterlist, you use an As clause to specify the data type of the argument to be passed to each parameter.

    注意

    如果未針對 .NET Framework 寫入外部程式,您必須注意資料類型對應。If the external procedure was not written for the .NET Framework, you must take care that the data types correspond. 例如,如果您使用 Integer 參數(Visual Basic 6.0 中的16位)來宣告 Visual Basic 6.0 程式的外部參考,則必須將對應的引數識別為 Declare 語句中的 Short,因為這是 Visual Basic 中的16位整數類型。For example, if you declare an external reference to a Visual Basic 6.0 procedure with an Integer parameter (16 bits in Visual Basic 6.0), you must identify the corresponding argument as Short in the Declare statement, because that is the 16-bit integer type in Visual Basic. 同樣地,Long 在 Visual Basic 6.0 中有不同的資料寬度,而 Date 則以不同的方式執行。Similarly, Long has a different data width in Visual Basic 6.0, and Date is implemented differently.

  • 傳回資料類型。Return Data Type. 如果外部程式是 Function 而且 Option StrictOn,您就必須指定傳回給呼叫程式碼之值的資料類型。If the external procedure is a Function and Option Strict is On, you must specify the data type of the value returned to the calling code. 這可以是任何資料類型,或是列舉、結構、類別或介面的名稱。This can be any data type or the name of an enumeration, structure, class, or interface.

    注意

    Visual Basic 編譯器不會驗證您的資料類型是否與外部程式的相容。The Visual Basic compiler does not verify that your data types are compatible with those of the external procedure. 如果出現不相符的情況,common language runtime 會在執行時間產生 MarshalDirectiveException 的例外狀況。If there is a mismatch, the common language runtime generates a MarshalDirectiveException exception at run time.

  • 預設資料類型。Default Data Types. 如果 Option StrictOff,而您未在 parameterlist中指定參數的資料類型,則 Visual Basic 編譯器會將對應的引數轉換為Object 資料類型If Option Strict is Off and you do not specify the data type of a parameter in parameterlist, the Visual Basic compiler converts the corresponding argument to the Object Data Type. 同樣地,如果您未指定 returntype,編譯器會將傳回資料類型設為 ObjectSimilarly, if you do not specify returntype, the compiler takes the return data type to be Object.

    注意

    由於您正在處理的外部程式可能是在不同的平臺上撰寫的,因此,對資料類型或允許其預設值的任何假設都是危險的。Because you are dealing with an external procedure that might have been written on a different platform, it is dangerous to make any assumptions about data types or to allow them to default. 指定每個參數的資料類型和傳回值(如果有的話),會比較安全。It is much safer to specify the data type of every parameter and of the return value, if any. 這也可以改善程式碼的可讀性。This also improves the readability of your code.

行為Behavior

  • 範圍.Scope. 外部參考在其類別、結構或模組的範圍內。An external reference is in scope throughout its class, structure, or module.

  • 期.Lifetime. 外部參考具有與宣告所在的類別、結構或模組相同的存留期。An external reference has the same lifetime as the class, structure, or module in which it is declared.

  • 呼叫外部程式。Calling an External Procedure. 您以呼叫 FunctionSub 程式的相同方式呼叫外部程式(如果它傳回值,則在運算式中使用它),或在呼叫語句中指定它(如果未傳回值)。You call an external procedure the same way you call a Function or Sub procedure—by using it in an expression if it returns a value, or by specifying it in a Call Statement if it does not return a value.

    您將引數傳遞給外部程式的方式,與 Declare 語句中 parameterlist 所指定的完全相同。You pass arguments to the external procedure exactly as specified by parameterlist in the Declare statement. 請勿將參數原本在外部檔案中宣告的方式納入考慮。Do not take into account how the parameters were originally declared in the external file. 同樣地,如果有傳回值,請使用與 Declare 語句中 returntype 所指定的相同。Similarly, if there is a return value, use it exactly as specified by returntype in the Declare statement.

  • 字元集。Character Sets. 您可以在 charsetmodifier 中指定 Visual Basic 應如何在呼叫外部程式時封送處理字串。You can specify in charsetmodifier how Visual Basic should marshal strings when it calls the external procedure. Ansi 修飾詞會指示 Visual Basic 將所有字串封送處理為 ANSI 值,而 Unicode 修飾詞會指示它將所有字串封送處理成 Unicode 值。The Ansi modifier directs Visual Basic to marshal all strings to ANSI values, and the Unicode modifier directs it to marshal all strings to Unicode values. Auto 修飾詞會指示 Visual Basic 根據外部參考 name的 .NET Framework 規則封送處理字串,或 aliasname (如果指定的話)。The Auto modifier directs Visual Basic to marshal strings according to .NET Framework rules based on the external reference name, or aliasname if specified. 預設值是 AnsiThe default value is Ansi.

    charsetmodifier 也會指定 Visual Basic 如何查詢其外部檔案中的外部程式。charsetmodifier also specifies how Visual Basic should look up the external procedure within its external file. AnsiUnicode 直接 Visual Basic 在搜尋期間不修改其名稱來進行查詢。Ansi and Unicode both direct Visual Basic to look it up without modifying its name during the search. Auto 會指示 Visual Basic 判斷執行時間平臺的基底字元集,而且可能會修改外部程式名稱,如下所示:Auto directs Visual Basic to determine the base character set of the run-time platform and possibly modify the external procedure name, as follows:

    • 在 ANSI 平臺上(例如 Windows 95、Windows 98 或 Windows Millennium Edition),請先查閱外部程式而不修改名稱。On an ANSI platform, such as Windows 95, Windows 98, or Windows Millennium Edition, first look up the external procedure with no name modification. 如果失敗,請將 "A" 附加至外部程式名稱的結尾,然後重新查詢。If that fails, append "A" to the end of the external procedure name and look it up again.

    • 在 Unicode 平臺上(例如 Windows NT、Windows 2000 或 Windows XP),請先查閱外部程式而不修改名稱。On a Unicode platform, such as Windows NT, Windows 2000, or Windows XP, first look up the external procedure with no name modification. 如果失敗,請將 "W" 附加至外部程式名稱的結尾,然後重新查詢。If that fails, append "W" to the end of the external procedure name and look it up again.

  • 機構.Mechanism. Visual Basic 使用 .NET Framework平台叫用(PInvoke)機制來解析和存取外部程式。Visual Basic uses the .NET Framework platform invoke (PInvoke) mechanism to resolve and access external procedures. Declare 語句和 DllImportAttribute 類別都會自動使用這項機制,而且您不需要任何的 PInvoke 知識。The Declare statement and the DllImportAttribute class both use this mechanism automatically, and you do not need any knowledge of PInvoke. 如需詳細資訊,請參閱逐步解說:呼叫 Windows apiFor more information, see Walkthrough: Calling Windows APIs.

重要

如果外部程式是在 common language runtime (CLR)外部執行,則為非受控碼If the external procedure runs outside the common language runtime (CLR), it is unmanaged code. 當您呼叫這類程式(例如,Windows API 函式或 COM 方法)時,可能會讓您的應用程式暴露于安全性風險下。When you call such a procedure, for example a Windows API function or a COM method, you might expose your application to security risks. 如需詳細資訊,請參閱安全的非受控碼程式碼撰寫方針For more information, see Secure Coding Guidelines for Unmanaged Code.

範例Example

下列範例會宣告傳回目前使用者名稱之 Function 程式的外部參考。The following example declares an external reference to a Function procedure that returns the current user name. 然後,它會呼叫外部程式 GetUserNameA 做為 getUser 程式的一部分。It then calls the external procedure GetUserNameA as part of the getUser procedure.

Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (
    ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
Sub GetUser()
    Dim buffer As String = New String(CChar(" "), 25)
    Dim retVal As Integer = GetUserName(buffer, 25)
    Dim userName As String = Strings.Left(buffer, InStr(buffer, Chr(0)) - 1)
    MsgBox(userName)
End Sub

範例Example

DllImportAttribute 提供在非受控碼中使用函數的替代方式。The DllImportAttribute provides an alternative way of using functions in unmanaged code. 下列範例會宣告已匯入的函式,而不使用 Declare 語句。The following example declares an imported function without using a Declare statement.

' Add an Imports statement at the top of the class, structure, or
' module that uses the DllImport attribute.
Imports System.Runtime.InteropServices
<DllImportAttribute("kernel32.dll", EntryPoint:="MoveFileW",
    SetLastError:=True, CharSet:=CharSet.Unicode,
    ExactSpelling:=True,
    CallingConvention:=CallingConvention.StdCall)>
Public Shared Function MoveFile(ByVal src As String,
  ByVal dst As String) As Boolean
    ' This function copies a file from the path src to the path dst.
    ' Leave this function empty. The DLLImport attribute forces calls
    ' to MoveFile to be forwarded to MoveFileW in KERNEL32.DLL.
End Function

請參閱See also