我在 Visual Studio 2015 解决方案中有多个项目。其中几个项目执行 P/Invokes,例如:
[DllImport("IpHlpApi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int GetIpNetTable(IntPtr pIpNetTable, [MarshalAs(UnmanagedType.U4)]
ref int pdwSize, bool bOrder);
因此,我将所有 P/Invokes 移至单独的类库,并将单个类定义为:
namespace NativeMethods
{
[
SuppressUnmanagedCodeSecurityAttribute(),
ComVisible(false)
]
public static class SafeNativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int GetTickCount();
// Declare the GetIpNetTable function.
[DllImport("IpHlpApi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
public static extern int GetIpNetTable(IntPtr pIpNetTable, [MarshalAs(UnmanagedType.U4)]
ref int pdwSize, bool bOrder);
}
}
在其他项目中,此代码称为:
int result = SafeNativeMethods.GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false);
所有编译都没有错误或警告。
现在在代码上运行 FxCop 会给出警告:
警告 CA1401 更改 P/Invoke 'SafeNativeMethods.GetIpNetTable(IntPtr, ref int, bool)' 的可访问性,使其不再从其程序集外部可见。
好的。将可访问性更改为 internal 为:
[DllImport("IpHlpApi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern int GetIpNetTable(IntPtr pIpNetTable, [MarshalAs(UnmanagedType.U4)]
ref int pdwSize, bool bOrder);
现在导致以下硬错误:
错误 CS0122 'SafeNativeMethods.GetIpNetTable(IntPtr, ref int, bool)' 由于其保护级别而无法访问
那么我怎样才能在没有错误或警告的情况下完成这项工作呢?
提前感谢您的帮助,因为我已经转了几个小时!