c# - DllImport 放在哪里?

标签 c# dllimport

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

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

最佳答案

你把它放在你从 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 - This class does not suppress stack walks for unmanaged code permission. (System.Security.SuppressUnmanagedCodeSecurityAttribute must not be applied to this class.) This class is for methods that can be used anywhere because a stack walk will be performed.

  • SafeNativeMethods - This class suppresses stack walks for unmanaged code permission. (System.Security.SuppressUnmanagedCodeSecurityAttribute is applied to this class.) This class is for methods that are safe for anyone to call. Callers of these methods are not required to perform a full security review to make sure that the usage is secure because the methods are harmless for any caller.

  • UnsafeNativeMethods - This class suppresses stack walks for unmanaged code permission. (System.Security.SuppressUnmanagedCodeSecurityAttribute is applied to this class.) This class is for methods that are potentially dangerous. Any caller of these methods must perform a full security review to make sure that the usage is secure because no stack walk will be performed.

关于c# - DllImport 放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6076717/

相关文章:

c#更新时闪烁的Listview

c++ - 可以在同一个应用程序中加载不同版本的 DLL 吗?

dll - pinvoke 字符串中仅传递第一个字符

c# - SHGetFileInfo : Description for a files extension too short

c# - 是否可以遍历枚举中的每个选择?

c# - 如何编写一个在 C# 中打开图像的方法,该方法将使用移动设备上的默认图像查看器...?

c# - 此示例代码中是否需要“异步/等待”?

java - 如何复制 Android 的股票相机方向变化

c# - 使用 C++ dll 函数提高 C# 项目的性能

.net - 围绕 AdbWinApi.dll 编写一个 .Net 包装器