【发布时间】:2011-08-29 22:07:45
【问题描述】:
static class Class
{
public static void methodRequiringStuffFromKernel32()
{
// code here...
}
}
我在哪里把[DllImport("Kernel32.dll")]放在这里?
【问题讨论】:
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 - 此类不会禁止非托管代码权限的堆栈遍历。 (System.Security.SuppressUnmanagedCodeSecurityAttribute 不得应用于此类。)此类用于可在任何地方使用的方法,因为将执行堆栈遍历。
SafeNativeMethods - 此类禁止堆栈遍历以获得非托管代码权限。 (System.Security.SuppressUnmanagedCodeSecurityAttribute 应用于此类。)此类用于任何人都可以安全调用的方法。这些方法的调用者不需要执行完整的安全审查以确保使用安全,因为这些方法对任何调用者都是无害的。
UnsafeNativeMethods - 此类禁止堆栈遍历以获得非托管代码权限。 (System.Security.SuppressUnmanagedCodeSecurityAttribute 应用于此类。)此类用于具有潜在危险的方法。这些方法的任何调用者都必须执行全面的安全审查,以确保使用安全,因为不会执行堆栈遍历。
【讨论】:
NativeMethods、SafeNativeMethods 或UnsafeNativeMethods (Naming Convention for Unmanaged Code Methods)。 C# 编译器在这种情况下应用了一些魔法。
NativeMethods 或变体只是约定。让它应用魔法的是System.Security.SuppressUnmanagedCodeSecurityAttribute,这是由 CLR 完成的,而不是编译器。
System.Runtime.InteropServices;
这是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。
【讨论】:
static class Class
{
[DllImport("kerynel32.dll")]
public static extern void methodRequiringStuffFromKernel32();
}
它继续 P/Invoking 外部方法的方法本身。确保添加对System.Runtime.InteropServices的引用
【讨论】: