分享

extern \调用系统API

 秋水风帆 2010-11-18
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);
            }
            }

Collapse 图像示例 3

说明

该示例使用两个文件 CM.csCmdll.c 来说明 extern。C 文件是示例 2 中创建的外部 DLL,它从 C# 程序内调用。

代码

  CopyCode image复制代码
// 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));
            }
            }

Collapse 图像输出

 
SampleMethod() returns 50.

Collapse 图像备注

生成项目:

  • 使用 Visual C++ 命令行将 Cmdll.c 编译为 DLL:

    cl /LD /MD Cmdll.c

  • 使用命令行编译 CM.cs

    csc CM.cs

这将创建可执行文件 CM.exe。运行此程序时,SampleMethod 将值 5 传递到 DLL 文件,该文件将此值乘以 10 返回。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多