static class Class
{
public static void methodRequiringStuffFromKernel32()
{
// code here...
}
}
我应该把[DllImport("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
。更多详情请参见非托管代码方法的命名约定。
CA1060: 将 P/Invoke 移动到 NativeMethods 类中:
NativeMethods - 此类不会抑制对非托管代码权限的栈遍历。(不能将System.Security.SuppressUnmanagedCodeSecurityAttribute应用于此类。)此类是为可以在任何地方使用的方法而设计的,因为将执行堆栈遍历。
SafeNativeMethods - 此类抑制对非托管代码权限的栈遍历。(Sysmtem.Security.SuppressUnmanagedCodeSecurityAttribute应用于此类。)此类是为安全调用者调用的方法而设计的。这些方法对于任何调用者都是无害的,因此调用者不需要执行完整的安全审核来确保使用是安全的。
UnsafeNativeMethods - 此类抑制对非托管代码权限的栈遍历。(Sysmtem.Security.SuppressUnmanagedCodeSecurityAttribute应用于此类。)此类是为潜在危险的方法而设计的。这些方法的任何调用者必须执行完整的安全审核来确保使用是安全的,因为不会执行堆栈遍历。
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);
}
}
static class Class
{
[DllImport("kerynel32.dll")]
public static extern void methodRequiringStuffFromKernel32();
}
这涉及到方法本身,即在外部调用P/Invoke方法。请确保添加对System.Runtime.InteropServices
的引用。
NativeMethods
、SafeNativeMethods
或UnsafeNativeMethods
(非托管代码方法的命名约定)。在这种情况下,C#编译器会应用一些特殊的操作。 - dtbSystem.Security.SuppressUnmanagedCodeSecurityAttribute
,这是由CLR而不是编译器完成的。 - Cody GraySystem.Runtime.InteropServices;
。 - Darren Griffith