extern 修饰符

extern(C# 参考)


extern 修饰符用于声明在外部实现的方法。 extern 修饰符的常见用法是在使用 Interop 服务调入非托管代码时与 DllImport 特性一起使用。在这种情况下,还必须将方法声明为 static,如下面的示例所示:

[DllImport("avifil32.dll")]
private static extern void AVIFileInit();

extern 关键字还可以定义外部程序集别名,使得可以从单个程序集中引用同一组件的不同版本。

将 abstract 和 extern 修饰符一起使用来修改同一成员是错误的做法。使用 extern 修饰符意味着方法是在 C# 代码的外部实现的,而使用 abstract 修饰符意味着类中未提供方法实现。
extern 关键字用于 C# 中时会比用于 C++ 中时受到更多的限制。

示例 1. 在此示例中,程序接收来自用户的字符串并将该字符串显示在消息框中。程序使用从 User32.dll 库导入的 MessageBox 方法。

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        [DllImport("User32.dll", CharSet = CharSet.Unicode)]
        public static extern int MessageBox(IntPtr h, string m, string c, int type);

        static void Main(string[] args)
        {
            string myString;
            Console.Write("Enter your message:");
            myString = Console.ReadLine();
            MessageBox((IntPtr)0, myString, "my Message Box:", 0);

        }
    }
}

  

示例 2. 此示例阐释了调入 C 库(本机 DLL)的 C# 程序。
1.1 创建以下 C 文件并将其命名为 cmdll.c:

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

1.2 从 Visual Studio 安装目录打开 Visual Studio x64(或 x32)本机工具命令提示符窗口,并通过在命令提示符处键入 CL /LD cmdll.c 来编译 cmdll.c 文件。


2.1.在相同的目录中,创建以下 C# 文件并将其命名为 cm.cs: 

// 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));
Console.ReadLine(); } }

  

2.2.从 Visual Studio 安装目录打开一个 Visual Studio x64(或 x32)本机工具命令提示符窗口,并通过键入以下内容来编译 cm.cs 文件:

csc cm.cs(针对 x64 命令提示符)
- 或 -
csc /platform:x86 cm.cs(针对 x32 命令提示符)
这将创建可执行文件 cm.exe。


3.运行 cm.exe。 SampleMethod 方法将值 5 传递到 DLL 文件,这将返回该值与 10 相乘后的结果。程序生成以下输出:

SampleMethod() returns 50.

其他参考资料:

在 C# 中通过 P/Invoke 调用Win32 DLL

https://msdn.microsoft.com/zh-cn/library/aa686045.aspx

原文地址:https://www.cnblogs.com/gsk99/p/4987437.html