extern

C# 程序員參考 
extern(C# 參考)

extern 修飾符用於聲明在外部實現的方法。extern 修飾符的常見用法是在使用 Interop 服務調入非託管代碼時與 DllImport 屬性一起使用;在這種情況下,該方法還必須聲明爲 static,如下面的示例所示:
 
[DllImport("avifil32.dll")]
private static extern void AVIFileInit();
 
注意
extern 關鍵字還可以定義外部程序集別名,使得可以從單個程序集中引用同一組件的不同版本。有關更多信息,請參見外部別名(C# 參考)。
 

將 abstract(C# 參考)和 extern 修飾符一起使用來修改同一成員是錯誤的。使用 extern 修飾符意味着方法在 C# 代碼的外部實現,而使用 abstract 修飾符意味着在類中未提供方法實現。

注意
extern 關鍵字在使用上比在 C++ 中有更多的限制。若要與 C++ 關鍵字進行比較,請參見 C++ Language Reference 中的 Using extern to Specify Linkage。
 

示例 1
說明
在該示例中,程序接收來自用戶的字符串並將該字符串顯示在消息框中。程序使用從 User32.dll 庫導入的 MessageBox 方法。

代碼
 
using System;
using System.Runtime.InteropServices;
class MainClass
{
    [DllImport("User32.dll")]
    public static extern int MessageBox(int h, string m, string c, int type);

    static int Main()
    {
        string myString;
        Console.Write("Enter your message: ");
        myString = Console.ReadLine();
        return MessageBox(0, myString, "My Message Box", 0);
    }
}
 

示例 2
說明
此示例創建一個外部 DLL,它將從示例 3 中的 C# 程序內調用。

代碼
  
// cmdll.c
// compile with: /LD /MD
int __declspec(dllexport) SampleMethod(int i)
{
    return i*10;
}
 

示例 3
說明
該示例使用兩個文件 CM.cs 和 Cmdll.c 來說明 extern。C 文件是示例 2 中創建的外部 DLL,它從 C# 程序內調用。

代碼
 
// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass
{
    [DllImport("Cmdll.dll")]
    public static extern int SampleMethod(int x);
    static void Main()
    {
        Console.WriteLine("SampleMethod() returns {0}.",
                SampleMethod(5));
    }
}
 

輸出
 
SampleMethod() returns 50.
 

備註
生成項目:

使用 Visual C++ 命令行將 Cmdll.c 編譯爲 DLL:

cl /LD /MD Cmdll.c

使用命令行編譯 CM.cs:

csc CM.cs

這將創建可執行文件 CM.exe。運行此程序時,SampleMethod 將值 5 傳遞到 DLL 文件,該文件將此值乘以 10 返回。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章