CA1415:P/Invokes 必須正確宣告
型別名稱 |
DeclarePInvokesCorrectly |
CheckId |
CA1415 |
分類 |
Microsoft.Interoperability |
中斷變更 |
非中斷 - 如果無法在組件外部看見宣告參數的 P/Invoke。中斷 - 如果可以在組件外部看見宣告參數的 P/Invoke。 |
原因
不正確地宣告平台叫用 (Invoke) 方法。
規則描述
平台叫用方法會存取 Unmanaged 程式碼,而且是使用 Visual Basic 中之 Declare 關鍵字或 DllImportAttribute 所定義的。目前,此規則會尋找以 Win32 函式為目標 (具有指向 OVERLAPPED 結構參數的指標) 的平台叫用方法宣告,且相對應的 Managed 參數不是指向 NativeOverlapped 結構的指標。
如何修正違規
若要修正此規則的違規情形,請正確地宣告平台叫用方法。
隱藏警告的時機
請勿隱藏此規則的警告。
範例
下列範例會顯示違反此規則和滿足此規則的平台叫用方法。
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);
}
}