Share via


PInvoke entry points should exist

TypeName

PInvokeEntryPointsShouldExist

CheckId

CA1400

Category

Microsoft.Interoperability

Breaking Change

NonBreaking

Cause

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.

Rule Description

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.

How to Fix Violations

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.

When to Exclude Warnings

Do not exclude 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 exclude a warning from this rule in the case where the unmanaged library could not be located.

Example

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.
      [DllImport("kernel32.dll")]
      public static extern void DoSomethingUnmanaged();
   }
}

See Also

Reference

System.Runtime.InteropServices.DllImportAttribute