extern(C# 參考)

來源:互聯網
上載者:User
   extern修飾符用於聲明在外部實現的方法。
   extern 修飾符的常見用法是在使用 Interop 服務調入Unmanaged 程式碼時與 DllImport 屬性一起使用;在這種情況下,該方法還必須聲明為 static,如下面的樣本所示:
    [DllImport("avifil32.dll")]
    private static extern void AVIFileInit();

注意 
   extern 關鍵字還可以定義外部程式集別名,使得可以從單個程式集中引用同一組件的不同版本。
 將 abstract 和 extern 修飾符一起使用來修改同一成員是錯誤的。

使用 
   extern 修飾符意味著方法在 C# 代碼的外部實現,而使用 abstract 修飾符意味著在類中未提供方法實現。注意 extern 關鍵字在使用上比在 C++ 中有更多的限制。
 
樣本 
   在該樣本中,程式接收來自使用者的字串並將該字串顯示在訊息框中。程式使用從 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);
}
}
 此樣本使用 C 程式建立一個 DLL,在下一樣本中將從 C# 程式調用該 DLL。
// cmdll.c // compile with:
/LD int __declspec(dllexport) SampleMethod(int i)
{
 return i*10;
 }
該樣本使用兩個檔案 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 Cmdll.c 使用命令列編譯 CM.cs: csc CM.cs 這將建立可執行檔 CM.exe。運行此程式時,SampleMethod 將值 5 傳遞到 DLL 檔案,該檔案將此值乘以 10 返回。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.