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 : 请注意,该类应命名为 NativeMethods
、SafeNativeMethods
或 UnsafeNativeMethods
。参见 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/