不要濫用 KEY_WOW64_64KEY


在 64-bit OS 開發過注冊表的人都應該知道, 其訪問存在 redirect. 

我曾經開發過一個注冊表程序, 涉及到會在 64-bit Windows 下運行, 翻看 MSDN 有一句話是這樣說的: 看加紅字體

KEY_WOW64_32KEY (0x0200)

Indicates that an application on 64-bit Windows should operate on the 32-bit registry view. This flag is ignored by 32-bit Windows. For more information, see Accessing an Alternate Registry View.

This flag must be combined using the OR operator with the other flags in this table that either query or access registry values.

Windows 2000:  This flag is not supported.

KEY_WOW64_64KEY (0x0100)

Indicates that an application on 64-bit Windows should operate on the 64-bit registry view. This flag is ignored by 32-bit Windows. For more information, see Accessing an Alternate Registry View.

This flag must be combined using the OR operator with the other flags in this table that either query or access registry values.

Windows 2000:  This flag is not supported.

 

我發揮了程序員最擅長的歸納聯想能力, 並想出來一個 "完美" 的解決方法: 既然 32-bit OS 會忽略KEY_WOW64_64KEY 和 KEY_WOW64_32KEY 標志位, 那么在所有程序中使用 KEY_WOW64_64KEY 這個標志. 即使程序運行在 32-bit OS 上, 有這個標志位也不會有什么作用. 然而到了 64-bit OS 中, 我企圖完全通過 key 的路徑來控制程序了. 於是我是這樣做的:

LONG rtn = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Wow6432Node\\Microsoft\\Office", 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, &hKey);

上述代碼在 Win 7 x64 下工作正常, 我以為我找到了全解.

 

就在我得意的時候, Tester 告訴我 Vista x64 上程序運行有問題. 問題很快被確定為注冊表讀取失敗, 但是為何失敗卻不知道, 系統返回了無法找到該鍵的錯誤代碼 2. 我仔細查看注冊表, 反復對比反復嘗試, 還是失敗. 我開始懷疑虛擬機會不會有什么特殊的影響, 抱着對程序的自信, 我竟然在虛擬機的 Vista x64 上安裝了 vs 2010! 一步一步調試, 最后發現 RegOpenKeyEx() 這里確實是失敗了. 我反復思考, 突然想起一片博客上看到了一句話: Never handle "Wow6432Node" yourself. 其原文鏈接我已經找不到了.

 

抱着嘗試, 我修改了代碼:

REGSAM flag = KEY_WOW64_32KEY or KEY_WOW64_64KEY;       // 偽代碼
LONG rtn = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Wow6432Node\\Microsoft\\Office", 0, KEY_ALL_ACCESS | flag, &hKey);


這次在 Vista x64 和 Win 7 x64 下工作正常. 

 

總結起來就是一句話: 使用標志位 KEY_WOW64_32KEY  KEY_WOW64_64KEY 來控制 HKEY_LOCAL_MACHINE\Software 的訪問, 如果你的程序可能會運行在 x64 Windows 上.

 

另:

一位網友(感謝 Tttavg)好心提醒, msdn 明確說明了兩者不能共存, msdn 說明如下: http://msdn.microsoft.com/en-us/library/windows/desktop/aa384129(v=vs.85).aspx

"

Either KEY_WOW64_32KEY or KEY_WOW64_64KEY can be specified. If both flags are specified, the function fails with ERROR_INVALID_PARAMETER.
  Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP: If both flags are specified, the function’s behavior is undefined.

"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM