Is there an elegant way to access protected members with gcc typeof & offsetof from outside the class?

206 Views Asked by At

I'm working on a project written in both C and C++. The C part has a macro used to get a pointer to an object from a pointer to one of its members

#define START_OF_OBJ(ptr, type, member)({\
    const __typeof__(((type *)0)->member)* mptr = (ptr);\
    (type *)((char *)mptr - __builtin_offsetof(type, member)); })

It works fine for structs, but not as well with pointers to protected members of C++ classes. E.g. when compiling

class A {
    public:
        int a;
        int *getb() { return &b; }

    protected:
        int b;
};

int main(void)
{
    A obj;

    int *pb = obj.getb();

    A* a = START_OF_OBJ(pb, A, b);
}

with g++ -Wno-invalid-offsetof, it will - as expected - report errors for ((type *)0)->member and __builtin_offsetof(type, member) for accessing a protected member variable.

Is there a more elegant solution than making the function using the macro a class friend?

0

There are 0 best solutions below