Partilhar via


CA1415: Declare P/Invokes correctly

Item Value
RuleId CA1415
Category Microsoft.Interoperability
Breaking change Non-breaking - If the P/Invoke that declares the parameter cannot be seen outside the assembly. Breaking - If the P/Invoke that declares the parameter can be seen outside the assembly.

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 suppress warnings

Do not suppress 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

Interoperating with Unmanaged Code