extern

本文介绍了 C# 中 extern 关键字的用途及示例,解释了如何使用 extern 调用非托管代码,并展示了如何从 C# 程序调用外部 DLL 的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值