This documentation is archived and is not being maintained.

P/Invoke entry points should exist







Breaking Change

Non Breaking

A public or protected method is marked with the System.Runtime.InteropServices.DllImportAttribute. Either the unmanaged library could not be located, or the method could not be matched to a function in the library. If the rule cannot find the method name exactly as specified, it looks for ANSI or wide-character versions of the method by suffixing the method name with 'A' or 'W'. If no match is found, the rule attempts to locate a function using the __stdcall name format (_MyMethod@12, where 12 represents the length of the arguments). If no match is found, and the method name begins with '#', the rule searches for the function as an ordinal reference instead of a name reference.

There is no compile-time check to ensure that methods marked with DllImportAttribute exist in the referenced unmanaged DLL. If no function that has the specified name exists in the library, or the arguments to the method do not match the function arguments, the common language runtime throws an exception.

To fix a violation of this rule, correct the method that has the DllImportAttribute attribute. Ensure the unmanaged library exists and is in the same directory as the assembly that contains the method. If the library is present and correctly referenced, verify that the method name, return type, and argument signature match the library function.

Do not suppress a warning from this rule when the unmanaged library is in the same directory as the managed assembly that references it. It might be safe to suppress a warning from this rule in the case where the unmanaged library could not be located.

The following example shows a type that violates the rule. There is no function named DoSomethingUnmanaged in kernel32.dll

using System.Runtime.InteropServices;

namespace InteroperabilityLibrary
   public class NativeMethods
      // If DoSomethingUnmanaged does not exist, or has  
      // a different signature or return type, the following  
      // code violates rule PInvokeEntryPointsShouldExist.
      public static extern void DoSomethingUnmanaged();