How to determine that two Win32 API handles represent the same object?

荒凉一梦 提交于 2019-12-21 05:24:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!