出于某种原因,如果应该打开句柄的方法失败,则安全句柄的最终确定会终止我的应用程序。
我有下一个非托管功能:
extern "C" __declspec(dllexport)
HRESULT
WINAPI
ConnectCommunicationPort(_Out_ PHANDLE hPort)
{
HRESULT hResult = FilterConnectCommunicationPort(FILEFILTER_PORT_NAME,
0,
NULL,
0,
NULL,
hPort);
return hResult;
}
FilterConnectCommunicationPort 被声明为
_Must_inspect_result_
HRESULT
WINAPI
FilterConnectCommunicationPort (
_In_ LPCWSTR lpPortName,
_In_ DWORD dwOptions,
_In_reads_bytes_opt_(wSizeOfContext) LPCVOID lpContext,
_In_ WORD wSizeOfContext,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_Outptr_ HANDLE *hPort
);
我有自定义的SafePortHandle类,如下所示:
public sealed class SafePortHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public SafePortHandle(IntPtr preexistingHandle, bool ownsHandle)
: base(ownsHandle)
{
SetHandle(preexistingHandle);
}
private SafePortHandle()
: base(true) { }
protected override bool ReleaseHandle()
{
if (IsInvalid)
{
return false;
}
return NativeMethods.CloseHandle(handle);
}
}
internal static class NativeMethods
{
DllImport("my.dll", SetLastError = true)]
internal static extern Hresult ConnectCommunicationPort(out SafePortHandle handle);
[DllImport("kernel32", SetLastError = true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(IntPtr handle);
}
internal static void Main(string[] args)
{
SafePortHandle _portHandle;
Hresult hr = NativeMethods.ConnectCommunicationPort(out _portHandle);
if (hr.Failed)
{
..
}
....
}
因此,如果FilterConnectCommunicationPort成功执行 - 一切正常,但如果FilterConnectCommunicationPort返回错误,我看到_portHandle无效(-1),并且在这种情况下终结kiils我的应用程序:外部组件抛出异常seh 0x80004005(那是未知错误)。这种情况发生在SafeHandle.InternalFinalize() .NET Framework方法中。
还尝试使用SafeFileHandle 完全按照我的需要工作,而不是SafePortHandle-相同的结果,应用程序崩溃。