Declare PInvokes correctly

TypeName

DeclarePInvokesCorrectly

CheckId

CA1415

Category

Microsoft.Interoperability

Breaking Change

NonBreaking, Breaking

Cause

A platform invoke method is incorrectly declared.

Rule Description

A platform invoke method accesses unmanaged code and is defined by using the Declare keyword in Visual Basic or the System.Runtime.InteropServices.DllImportAttribute. Currently, this rule looks for platform invoke method declarations that target Win32 functions that have a pointer to an OVERLAPPED structure parameter and the corresponding managed parameter is not a pointer to a System.Threading.NativeOverlapped structure.

How to Fix Violations

To fix a violation of this rule, correctly declare the platform invoke method.

When to Exclude Warnings

Do not exclude a warning from this rule.

Example

The following example shows platform invoke methods that violate the rule and satisfy the rule.

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace InteroperabilityLibrary
{
    // The platform invoke methods in this class violate the rule.
    [ComVisible(true)]
    internal class NativeMethods
    {
        private NativeMethods() { }

        [DllImport("kernel32.dll", SetLastError = true)]
        internal extern static uint ReadFile(
           IntPtr hFile, IntPtr lpBuffer, int nNumberOfBytesToRead,
           IntPtr lpNumberOfBytesRead, IntPtr overlapped);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal extern static bool ReadFileEx(
           IntPtr hFile, IntPtr lpBuffer, int nNumberOfBytesToRead,
           NativeOverlapped overlapped, IntPtr lpCompletionRoutine);
    }

    // The platform invoke methods in this class satisfy the rule.
    [ComVisible(true)]
    internal class UnsafeNativeMethods
    {
        private UnsafeNativeMethods() { }

        //To compile this code, uncomment these lines and compile
        //with "/unsafe".
        //[DllImport("kernel32.dll", SetLastError = true)]
        //unsafe internal extern static uint ReadFile(
        //   IntPtr hFile, IntPtr lpBuffer, int nNumberOfBytesToRead,
        //   IntPtr lpNumberOfBytesRead, NativeOverlapped* overlapped);

        //[DllImport("kernel32.dll", SetLastError = true)]
        //[return: MarshalAs(UnmanagedType.Bool)]
        //unsafe internal extern static bool ReadFileEx(
        //   IntPtr hFile, IntPtr lpBuffer, int nNumberOfBytesToRead,
        //   NativeOverlapped* overlapped, IntPtr lpCompletionRoutine);
    }
}

See Also

Other Resources

Interoperating with Unmanaged Code