简体   繁体   English

如何将指针地址转换为unsigned char数组?

[英]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? 如何将地址转换为unsigned char数组? 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; 如果你曾经使用多态,那么要非常小心 ,继承的对象可能比母类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? 既然你的问题被标记为C ++,我是否也建议你不要转换指针,而是尝试使用一些高级库? Qt provides an excellent framework for sockets, and boost probably too. Qt为套接字提供了一个很好的框架,并且也可能提升。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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