开发者

Convert into void*

how can I convert any object of my own class co开发者_如何学编程nvert into pointer to void?

MyClass obj;
(void*)obj; // Fail


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.


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


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

MyClass obj;
void *ptr = (void*)&obj; // Success!


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;


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

Perhaps: (void*)(&obj)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜