Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get pointer to object from pointer to some member

Tags:

Suppose there's a structure

struct Thing {   int a;   bool b; }; 

and I get a pointer to member b of that structure, say as parameter of some function:

void some_function (bool * ptr) {   Thing * thing = /* ?? */; } 

How do I get a pointer to the containing object? Most importantly: Without violating some rule in the standard, that is I want standard defined behaviour, not undefined nor implementation defined behaviour.

As side note: I know that this circumvents type safety.

like image 510
Daniel Jour Avatar asked Nov 23 '15 11:11

Daniel Jour


People also ask

How a pointer to an object can be used to access the member of that object?

The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .

How do you access the members of pointers?

To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this). The second step, use arrow operator -> to access the member function using the pointer to the object.

What does the -> operator allow you to do with respect to pointers to objects?

The "arrow" operator -> is used to dereference pointers to objects to get their members. So if you have a pointer an object in the variable ui and the object has a member pushButton then you can use ui->pushButton to access the pushButton member.


2 Answers

If you are sure that the pointer is really pointing to the member b in the structure, like if someone did

Thing t; some_function(&t.b); 

Then you should be able to use the offsetof macro to get a pointer to the structure:

std::size_t offset = offsetof(Thing, b); Thing* thing = reinterpret_cast<Thing*>(reinterpret_cast<char*>(ptr) - offset); 

Note that if the pointer ptr doesn't actually point to the Thing::b member, then the above code will lead to undefined behavior if you use the pointer thing.

like image 118
Some programmer dude Avatar answered Sep 29 '22 16:09

Some programmer dude


void some_function (bool * ptr) {   Thing * thing = (Thing*)(((char*)ptr) - offsetof(Thing,b)); } 

I think there is no UB.

like image 28
deviantfan Avatar answered Sep 29 '22 17:09

deviantfan