DllImport应该放在哪里?

11
static class Class    
{
    public static void methodRequiringStuffFromKernel32()
    {
        // code here...
    }
} 

我应该把[DllImport("Kernel32.dll")]放在哪里?

3个回答

14
你需要将其放在从Kernel32.dll导入的方法上。 例如,
static class Class    
{
    [DllImport("Kernel32.dll")]
    static extern Boolean Beep(UInt32 frequency, UInt32 duration);

    public static void methodRequiringStuffFromKernel32()
    {
        // code here...
        Beep(...);
    }
}

来自@dtb: 注意,类应该被命名为NativeMethodsSafeNativeMethodsUnsafeNativeMethods。更多详情请参见非托管代码方法的命名约定

CA1060: 将 P/Invoke 移动到 NativeMethods 类中

  • NativeMethods - 此类不会抑制对非托管代码权限的栈遍历。(不能将System.Security.SuppressUnmanagedCodeSecurityAttribute应用于此类。)此类是为可以在任何地方使用的方法而设计的,因为将执行堆栈遍历。

  • SafeNativeMethods - 此类抑制对非托管代码权限的栈遍历。(Sysmtem.Security.SuppressUnmanagedCodeSecurityAttribute应用于此类。)此类是为安全调用者调用的方法而设计的。这些方法对于任何调用者都是无害的,因此调用者不需要执行完整的安全审核来确保使用是安全的。

  • UnsafeNativeMethods - 此类抑制对非托管代码权限的栈遍历。(Sysmtem.Security.SuppressUnmanagedCodeSecurityAttribute应用于此类。)此类是为潜在危险的方法而设计的。这些方法的任何调用者必须执行完整的安全审核来确保使用是安全的,因为不会执行堆栈遍历。


3
注意,该类应命名为NativeMethodsSafeNativeMethodsUnsafeNativeMethods非托管代码方法的命名约定)。在这种情况下,C#编译器会应用一些特殊的操作。 - dtb
2
只是出于好奇:会应用什么编译器魔法?该链接仅说明了一些命名指南,但没有描述任何编译器魔法。您有进一步研究的链接吗? - PetPaulsen
@PetPaulsen:这是与安全相关的编译器魔法 :-) 说实话,我不知道它确切的作用;如果你不这样做,FxCop就会抱怨。我已经在答案中添加了一句来自FxCop文档的引用。 - dtb
1
@dtb:C#编译器在这里不会应用任何魔法,也不是基于类的名称来执行此操作。将其称为“NativeMethods”或其变体只是惯例。使其应用魔法的内容是System.Security.SuppressUnmanagedCodeSecurityAttribute,这是由CLR而不是编译器完成的。 - Cody Gray
不要忘记使用 System.Runtime.InteropServices; - Darren Griffith

6
这是一个 DllImport 的示例:
using System;
using System.Runtime.InteropServices;

class MsgBoxTest
{
  [DllImport("user32.dll")]
  static extern int MessageBox (IntPtr hWnd, string text, string caption,
                                int type);
  public static void Main()
  {
    MessageBox (IntPtr.Zero, "Please do not press this again.", "Attention", 0);
  }
}

我建议你学习平台调用教程。链接为:Platform Invoke 教程

1
static class Class    
{
    [DllImport("kerynel32.dll")]
    public static extern void methodRequiringStuffFromKernel32();

}

这涉及到方法本身,即在外部调用P/Invoke方法。请确保添加对System.Runtime.InteropServices的引用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接