extern \调用系统API

来源:百度文库 编辑:神马文学网 时间:2024/04/26 03:39:08
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); } }
示例 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 返回。