Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

CA1415: Declare P/Invokes correctly

TypeName

DeclarePInvokesCorrectly

CheckId

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.

A platform invoke method is incorrectly declared.

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.

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

Do not suppress a warning from this rule.

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);
    }
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.