问题
Suppose I have two hanldes:
HANDLE h1;
HANDLE h2;
And both have received values resulted from some Windows API function - in particular, I'm interesed in handles resulted from calls to CreateFile()
. How do I determine that h1
and h2
reference the same underlying object - in the case of CreateFile()
- same file, directory or device? Is there some API to determine that?
回答1:
You could use GetFinalPathNameByHandle and compare the file path of both handles. https://msdn.microsoft.com/en-us/library/windows/desktop/aa364962(v=vs.85).aspx
回答2:
The GetFileInformationByHandle API returns information that can be used to uniquely identify the referenced object:
You can compare the VolumeSerialNumber and FileIndex members returned in the BY_HANDLE_FILE_INFORMATION structure to determine if two paths map to the same target; for example, you can compare two file paths and determine if they map to the same directory.
For example:
bool SameFile( HANDLE h1, HANDLE h2 ) {
BY_HANDLE_FILE_INFORMATION bhfi1 = { 0 };
BY_HANDLE_FILE_INFORMATION bhfi2 = { 0 };
if ( ::GetFileInformationByHandle( h1, &bhfi1 ) &&
::GetFileInformationByHandle( h2, &bhfi2 ) ) {
return ( ( bhfi1.nFileIndexHigh == bhfi2.nFileIndexHigh ) &&
( bhfi1.nFileIndexLow == bhfi2.nFileIndexLow ) &&
( bhfi1.dwVolumeSerialNumber == bhfi2.dwVolumeSerialNumber ) );
}
return false;
}
回答3:
New for Windows 10:
CompareObjectHandles - Compares two object handles to determine if they refer to the same underlying kernel object.
https://msdn.microsoft.com/en-us/library/windows/desktop/mt438733(v=vs.85).aspx
来源:https://stackoverflow.com/questions/29436696/how-to-determine-that-two-win32-api-handles-represent-the-same-object