How to gain Access to member variables of a class using void pointer but Not Object

后端 未结 6 1151
暖寄归人
暖寄归人 2021-01-24 21:29

I am trying to access member variables of a class without using object. please let me know how to go about.

class TestMem
{
    int a;
    int b;
public:
    Tes         


        
6条回答
  •  自闭症患者
    2021-01-24 22:19

    The "right" way to do this is by using the offsetof() macro from . Unfortunately offsetof() has some fairly draconian restrictions in C++:

    Because of the extended functionality of structs in C++, in this language, the use of offsetof is restricted to "POD [plain old data] types", which for classes, more or less corresponds to the C concept of struct (although non-derived classes with only public non-virtual member functions and with no constructor and/or destructor would also qualify as POD).

    So if you make a and b public and get rid of TestMem's constructor, you can write something like this to access a:

    C++ style:

    #include 
    
    int vala = *reinterpret_cast(reinterpret_cast(&o1)
               + offsetof(TestMem, a));
    

    C style:

    #include 
    
    int vala = *(int *) ((char *) &o1 + offsetof(TestMem, a));
    

    Notice that you need to use &o1 here, not p, which is a function pointer. The address of TestMem::TestMem1 won't have any relation to the locations of a and b. Class methods don't reside in memory anywhere near class member variables.


    The "wrong" way is to just guess at where a and b are in memory. Most likely they are at offsets 0 and 4 from the start of o1, respectively. So this code would work most of the time:

    int vala = *(int *) ((char *) &o1 + 0);
    int valb = *(int *) ((char *) &o1 + 4);
    

    There are a lot of assumptions here. This assumes that ints are 4 bytes and that there's no padding between a and b. On the other hand it doesn't have any of the restrictions from above: a and b don't need to be public, you can have a constructor, whatever.

提交回复
热议问题