在Windows驅動程式的編寫中,當我們調用一個返回NTSTATUS值的函數時(比如IoCreateDevice),應當檢查傳回值是否成功。
有人經常這樣寫
ntStatus = function(...);<br />if(STATUS_SUCCESS == ntStatus)<br /> ...
但是,這並不總是合理的。
在ddk標頭檔”ntdef.h“中,NTSTATUS是這樣定義的:
typedef __success(return >= 0) LONG NTSTATUS;<br />//<br />// Status values are 32 bit values layed out as follows:<br />//<br />// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1<br />// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0<br />// +---+-+-------------------------+-------------------------------+<br />// |Sev|C| Facility | Code |<br />// +---+-+-------------------------+-------------------------------+<br />//<br />// where<br />//<br />// Sev - is the severity code<br />//<br />// 00 - Success<br />// 01 - Informational<br />// 10 - Warning<br />// 11 - Error<br />//<br />// C - is the Customer code flag<br />//<br />// Facility - is the facility code<br />//<br />// Code - is the facility's status code<br />//
可見,NTSTATUS是一個有符號
的長整數。並且分為四個域。最高2位Sev域,描述的是這個NTSTATUS的嚴重性(Severity):
00 成功(Success)
01 資訊(Informational)
10 警告(Warning)
11 錯誤(Error)
00和01應該都表示成功的狀態,10和11都表示錯誤狀態。即對於這樣的有符號長整數的最高位(也就是符號位)
,0成功,1錯誤。那麼,如果NTSTATUS>=0為成功,NTSTATUS<0為錯誤。
因此,在標頭檔”ntdef.h“中,測試NTSTATUS成功的宏定義為:
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)<br />
而不是我以前想象的測試status == 0(STATUS_SUCCESS = 0)
參考我在StackOverflow上發的問題,感謝解答問題的老外^_^
http://stackoverflow.com/questions/3378622/how-to-understand-the-ntstatus-nt-success-typedef-in-windows-ddk/3378675