為什麼要用NT_SUCCESS()宏測試返回的NTSTATUS值

來源:互聯網
上載者:User

在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.