【问题标题】:How do you directly call a native function exported from a DLL?如何直接调用从 DLL 导出的本机函数?
【发布时间】:2012-04-12 11:07:07
【问题描述】:

如何直接调用从 DLL 导出的本机函数?谁能给我一个小例子?

【问题讨论】:

    标签: c#


    【解决方案1】:

    这是Microsoft example

    class PlatformInvokeTest
    {
        [DllImport("msvcrt.dll")]
        public static extern int puts(string c);
        [DllImport("msvcrt.dll")]
        internal static extern int _flushall();
    
        public static void Main() 
        {
            puts("Test");
            _flushall();
        }
    }
    

    如果您需要从本机 dll 生成 C# DLLImport 声明,请观看此帖子:Generate C# DLLImport declarations from a native dll

    【讨论】:

      【解决方案2】:

      取决于你到底想要什么......我的代码中有这样的东西,但它使用 Win32 API dll 的

      [DllImport("user32.dll")]
      static extern IntPtr GetForegroundWindow();
      

      然后打电话

       GetForegroundWindow()
      

      就像在类中定义的一样

      【讨论】:

        【解决方案3】:

        下面是DllImport 属性的一个简单示例:

        using System.Runtime.InteropServices;
        class C
        {
            [DllImport("user32.dll")]
            public static extern int MessageBoxA(int h, string m, string c, int type);
            public static int Main()
            {
                return MessageBoxA(0, "Hello World!", "Caption", 0);
            }
        }
        

        此示例显示了声明在本机 DLL 中实现的 C# 方法的最低要求。方法C.MessageBoxA() 使用static 和external 修饰符声明,并具有DllImport 属性,它告诉编译器实现来自user32.dll,使用默认名称消息框A

        参考this link

        【讨论】:

          猜你喜欢
          • 2011-08-25
          • 2011-01-17
          • 2011-01-16
          • 2019-04-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多