Export (0) Print
Expand All
Expand Minimize

Move pinvokes to native methods class

TypeName

MovePInvokesToNativeMethodsClass

CheckId

CA1060

Category

Microsoft.Design

Breaking Change

Breaking

A method uses Platform Invocation Services to access unmanaged code and is not a member of one of the 'NativeMethods' classes.

Platform Invocation methods, such as those marked with the System.Runtime.InteropServices.DllImportAttribute attribute, or methods defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be in one of the following classes:

  • 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 do a full security review to ensure 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 do a full security review to ensure that the usage is secure because no stack walk will be performed.

These classes are declared as internal (Friend, in Visual Basic), and declare a private constructor to prevent new instances from being created. The methods in these classes should be static and internal (Shared and Friend in Visual Basic).

To fix a violation of this rule, move the method to the appropriate NativeMethods class.

Do not exclude a warning from this rule.

The following example declares a method that violates this rule.

Imports System

NameSpace MSInternalLibrary

' Violates rule: MovePInvokesToNativeMethodsClass.
Friend Class UnmanagedApi
    Friend Declare Function RemoveDirectory Lib "kernel32" ( _
       ByVal Name As String) As Boolean
End Class

End NameSpace 

Community Additions

ADD
Show:
© 2014 Microsoft