Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

Where do I put [DllImport("Kernel32.dll")] here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
373 views
Welcome To Ask or Share your Answers For Others

1 Answer

You put it on the method you're importing from Kernel32.dll.

For example,

static class Class    
{
    [DllImport("Kernel32.dll")]
    static extern Boolean Beep(UInt32 frequency, UInt32 duration);

    public static void methodRequiringStuffFromKernel32()
    {
        // code here...
        Beep(...);
    }
}

From @dtb: Note that the class should be named NativeMethods, SafeNativeMethods or UnsafeNativeMethods. See Naming Convention for Unmanaged Code Methods for more details.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...