I have an address or pointer to an object.
How do I convert the address to unsigned char array? I am using it as a reference to transport using sockets. Thanks.
I have an address or pointer to an object.
How do I convert the address to unsigned char array? I am using it as a reference to transport using sockets. Thanks.
Object * pObject = ...;
unsigned char * pSz = reinterpret_cast<unsigned char *>(pObject);
// thru pSz you can see your object blindly as a pointer of unsigned char
// (the first char is pointed)
//and only if you know the size of your object (sizeObject) you can do this:
unsigned char pArray[sizeObject] = pSz;
Be really carefull if you ever use polymorphism, inherited objects may have totally differents sizes than there mother class Object;
If the type are completely unrelated (which apparently they are), you probably need a reinterpret_cast
.
void *your_pointer;
unsigned char *new_pointer = (unsigned char*) your_pointer;
Since your question is tagged C++, may I also suggest that you don't convert pointers around, but try using some high-level library instead? Qt provides an excellent framework for sockets, and boost probably too.
unsigned char *array = reinterpret_cast<unsigned char*>(my_obj);
However, you shouldn't send your objects simply by treating them as byte array. There is some data over there, like method addresses which will be useless after sending over network.
void* ptr; // Could be any type of course
ptr = something();
int n = sizeof(ptr);
unsigned char arr = new unsigned char[n];
memcpy((void*)arr[0], (void*)ptr, n);
// Remember to delete [] the array