简体   繁体   中英

How to convert pointer address to unsigned char array?

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.

如果类型完全不相关(显然它们是),则可能需要reinterpret_cast

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM