Convert into void*
Asked Answered
E

6

6

how can I convert any object of my own class convert into pointer to void?

MyClass obj;
(void*)obj; // Fail
Enterpriser answered 30/6, 2011 at 11:47 Comment(4)
You can't. What are you trying to do?Strap
@bo-persson I have a structure which can store an additional info inside it by passing a void* data.Enterpriser
one you wrote or inherited? if former - why-o-why?Subclass
@nim That structure is from own library, I can't modify it.Enterpriser
D
13
MyClass obj;
void *p;

p = (void*)&obj; // Explicit cast.
// or:
p = &obj; // Implicit cast, as every pointer is compatible with void *

But beware ! obj is allocated on the stack this way, as soon as you leave the function the pointer becomes invalid.

Edit: Updated to show that in this case an explicit cast is not necessary since every pointer is compatible with a void pointer.

Damiano answered 30/6, 2011 at 11:49 Comment(7)
So, why is everyone explicitly casting to void*?Benedikt
Can I use shared_ptr for to controll the life?Enterpriser
@Cwan: Reflex. When I do some casting I almost always do it explicitly. Have updated my answer.Damiano
@Ockonal: No idea, my C++ is very, very rusty.Damiano
@DarkDust: Not every pointer is "compatible" (you mean, implicitly convertible) to void*. For example you can't convert a const char* to void* without a const_castHannis
Terminology: a cast is an explicit conversion. An implicit conversion is not a cast.Burgh
@Steve: Yeah, I should probably have been more precise and said "explicitly converting to void* using a cast".Benedikt
H
6

You cant convert a non-pointer to void*. You need to convert the pointer to your object to void*

(void*)(&obj); //no need to cast explicitly.

that conversion is implicit

void* p = &obj; //OK
Hannis answered 30/6, 2011 at 11:49 Comment(0)
B
5

If you use the address, you can convert it to a void pointer.

MyClass obj;
void *ptr = (void*)&obj; // Success!
Bohlen answered 30/6, 2011 at 11:49 Comment(0)
M
1

To do something which has any chance of being meaningful, first you have to take the address of an object, obtaining a pointer value; then cast the pointer.

MyClass obj;
MyClass * pObj = &obj;
void * pVoidObj = (void*)pObj;
Maternal answered 30/6, 2011 at 11:49 Comment(0)
B
1

i beleive you could only convert a pointer to an object to a pointer to void ???

Perhaps: (void*)(&obj)

Bismarck answered 30/6, 2011 at 11:50 Comment(0)
H
0

In addition to the technical answers: Assert, that you avoid multiple inheritance or else you don't assign the address of super-class interfaces to a void*, for they will not be unique! E.g.

class S1 { int u; };
class S2 { int v; };
class MyClass : public S1, public S2 {};

MyClass obj;
S2* s2 = &obj;
void * p1 = &obj;
void * p2 = s2;

Here p1 and p2 (==s2) will be different, because the S2 instance in C has an address offset.

Hawfinch answered 25/3, 2022 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.