Legit Uses of the offsetof Macro in C / C++

前端 未结 5 1655
囚心锁ツ
囚心锁ツ 2021-01-02 13:45

There is this macro offsetof in C/C++ which allows you to get the address offset of a member in a POD structure. For an example from the C FAQ:

struct foo {         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 13:47

    offsetof is relatively frequently used for device driver programming where you usually have to write in plain C but sometimes need some "other" features. Consider you have a callback function which gets pointer to some structure. Now this structure is itself is a member of another bigger "outer" structure. with "offsetof" you have ability to change the members of the "outer" structure when you have access only to the "inner" member.

    Something like this:

    struct A
    {
     int a1;
     int a2;
    };
    
    struct B
    {
     int b1;
     int b2;
     A a;
    };
    
    void some_API_callback_func(A * a)
    {
     //here you do offsetof 
     //to get access to B members
    }
    

    Of course this is dangerous if you have possibility that struct A is used not as part of struct B. But in many places where framework for "some_API_callback_func" is well documented this works fine.

提交回复
热议问题