在哪里放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 :请注意,该类应命名为NativeMethods
, SafeNativeMethods
或UnsafeNativeMethods
。 有关更多详细信息,请参阅命名非托管代码方法约定 。
CA1060:将P / Invokes移动到NativeMethods类 :
NativeMethods – 此类不会抑制非托管代码权限的堆栈遍历。 (System.Security.SuppressUnmanagedCodeSecurityAttribute不能应用于此类。)此类适用于可在任何地方使用的方法,因为将执行堆栈遍历。
SafeNativeMethods – 此类禁止堆栈遍历非托管代码权限。 (System.Security.SuppressUnmanagedCodeSecurityAttribute应用于此类。)此类适用于任何人都可以安全调用的方法。 这些方法的调用者不需要执行完整的安全性审查,以确保使用是安全的,因为这些方法对任何调用者都是无害的。
UnsafeNativeMethods – 此类禁止堆栈遍历以获取非托管代码权限。 (System.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 /调用外部方法的方法本身。 确保添加对System.Runtime.InteropServices
的引用