EDKII CR宏:根據成員指標擷取父結構體變數指標

來源:互聯網
上載者:User

標籤:

 

核心提示:

1. CR宏 (Containing Record):根據成員指標擷取父結構體變數指標

2. 0 指標的妙用。

 

在EDKII 的代碼中有不少關於CR宏的使用,如 時鐘中斷處理函數CoreTimerTick。

VOID EFIAPI CoreTimerTick (  IN UINT64   Duration  ) {  IEVENT          *Event;   ...  if (!IsListEmpty (&mEfiTimerList)) {    Event = CR (mEfiTimerList.ForwardLink, IEVENT, Timer.Link, EVENT_SIGNATURE);   ...  }}

 

CR宏的定義
  1. //  CONTAINING_RECORD - returns a pointer to the structure
  2. //      from one of it‘s elements.
  3. #define_CR(Record, TYPE, Field)  ((TYPE *) ((CHAR8 *) (Record) - (CHAR8 *) &(((TYPE *) 0)->Field)))
  4. #defineCR(Record, TYPE, Field, Signature)   \\par     _CR(Record, TYPE, Field)

 

CR的用法:  _CR (  結構體某成員變數的指標 Record, 結構體類型定義 TYPE, 結構體成員變數名 Field  );

這個宏定義的關鍵點是 0 指標。 結構體調用 Struct –> Member 是 把Struct的指標 加上 Member的位移量, 0->member的調用可以直接得到 member的位移量。 這樣把member的實際指標 減去 位移量,就是這個結構體本身的指標。 很巧妙的用法!

下面舉例說明:

CR宏的使用
  1. #include"stdafx.h"
  2.  
  3. #define  CHAR8  char
  4. //  CONTAINING_RECORD - returns a pointer to the structure
  5. //      from one of it‘s elements.
  6. #define_CR(Record, TYPE, Field)  ((TYPE *) ((CHAR8 *) (Record) - (CHAR8 *) &(((TYPE *) 0)->Field)))
  7. #defineCR(Record, TYPE, Field, Signature)   \\par     _CR(Record, TYPE, Field)
  8.  
  9. typedefstruct_MyStruct
  10. {
  11.     inta;
  12.     charb;
  13.     longc;
  14.     intd;
  15. } MyStruct;
  16.  
  17. int_tmain(intargc, _TCHAR* argv[])
  18. {
  19.     MyStructmyStruct = {10,‘a‘,30,25};    
  20.     printf("MyStruct Address 0x%x \n", &myStruct);    
  21.     MyStruct * pMyStruct = CR(&(myStruct.c), MyStruct, c, NULL);
  22.     printf("pMyStruct Address 0x%x \n", pMyStruct);
  23.  
  24.     getchar();
  25.     return 0;
  26. }

EDKII CR宏:根據成員指標擷取父結構體變數指標

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.