将 DllImport 放在哪里?

Posted

技术标签:

【中文标题】将 DllImport 放在哪里?【英文标题】:Where to put DllImport? 【发布时间】:2011-08-29 22:07:45 【问题描述】:
static class Class    

    public static void methodRequiringStuffFromKernel32()
    
        // code here...
    
 

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

【问题讨论】:

【参考方案1】:

你把它放在你从 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。详情请见Naming Convention for Unmanaged Code Methods。

CA1060: Move P/Invokes to NativeMethods class:

NativeMethods - 此类不会禁止非托管代码权限的堆栈遍历。 (System.Security.SuppressUnmanagedCodeSecurityAttribute 不得应用于此类。)此类用于可在任何地方使用的方法,因为将执行堆栈遍历。

SafeNativeMethods - 此类禁止堆栈遍历以获得非托管代码权限。 (System.Security.SuppressUnmanagedCodeSecurityAttribute 应用于此类。)此类用于任何人都可以安全调用的方法。这些方法的调用者不需要执行完整的安全审查以确保使用安全,因为这些方法对任何调用者都是无害的。

UnsafeNativeMethods - 此类禁止堆栈遍历以获得非托管代码权限。 (System.Security.SuppressUnmanagedCodeSecurityAttribute 应用于此类。)此类用于具有潜在危险的方法。这些方法的任何调用者都必须执行全面的安全审查,以确保使用安全,因为不会执行堆栈遍历。

【讨论】:

请注意,该类应命名为NativeMethodsSafeNativeMethodsUnsafeNativeMethods (Naming Convention for Unmanaged Code Methods)。 C# 编译器在这种情况下应用了一些魔法。 只是出于好奇:将应用什么编译器魔法?该链接仅说明了一些命名准则。但是没有描述编译器的魔法。你有进一步学习的链接吗? @PetPaulsen:这是与安全相关的编译器魔法 :-) Tbh,我不知道它到底是做什么的;当您不这样做时,FxCop 会抱怨。我在答案中添加了 FxCop 文档中的引用。 @dtb:C# 编译器在此处应用任何魔法,并且它不会根据类的名称这样做。将其称为NativeMethods 或变体只是约定。让它应用魔法的是System.Security.SuppressUnmanagedCodeSecurityAttribute,这是由 CLR 完成的,而不是编译器。 别忘了使用System.Runtime.InteropServices;【参考方案2】:

这是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 Tutorial。

【讨论】:

【参考方案3】:
static class Class    

    [DllImport("kerynel32.dll")]
    public static extern void methodRequiringStuffFromKernel32();


它继续 P/Invoking 外部方法的方法本身。确保添加对System.Runtime.InteropServices的引用

【讨论】:

以上是关于将 DllImport 放在哪里?的主要内容,如果未能解决你的问题,请参考以下文章

请问[DllImport("gpsapi.dll")]的dll文件放在哪儿?

在 .NET 中指定 DllImport 的搜索路径

Objective-C - 将 NSNotificationCenter 放在哪里?

我将所有这些接口放在哪里?

将 Erlang 版本运行的数据放在哪里

将多次访问的具有常量值的数组放在哪里?