dbt
dbt

Reputation: 113

Cast the object pointed by (void*) to char[]

I'm trying to cast some objects (the size is known) pointed by void* to a char array bitwisely in c++. I'm considering using union with a char array so that I don't need to worry too much about the casting. However, since the type of the object is unknown, I don't know how to define this union.

Just wondering if there is any other better way to deal with this?

PS: edited to avoid confusion. For instance, an integer could be cast to a 4-character array.

Thanks!

Upvotes: 2

Views: 1353

Answers (4)

Paul Evans
Paul Evans

Reputation: 27577

From 5.2.10 Reinterpret cast:

An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast(static_cast(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment requirements of T2 are no stricter than those of T1, or if either type is void.

So you simply want to use:

char* my_bytes = reinterpret_cast<char*>(my_pointer); 
size_t num_bytes = sizeof(my_pointer);
for(size_t i = 0; i < num_bytes; ++i) {
   // *(my_bytes + i) has the most significant to least significant bytes
}

Upvotes: 1

R Sahu
R Sahu

Reputation: 206577

If you are not worried about a bit of extra memory, you can use memcpy.

int i = 10;
char carray[sizeof(i)];
memcpy(carray, &i, sizeof(i));

However, remember that carray won't be a null terminated string. It will be just an array of chars. It will be better to use unsigned char since the value in one of those bytes might be too large for char if char is a signed type on your platform.

int i = 10;
unsigned char carray[sizeof(i)];
memcpy(carray, &i, sizeof(i));

Upvotes: 1

Jordan M
Jordan M

Reputation: 1243

Why do you feel you need to worry about the casting?

Just reinterpret_cast the void pointer to a char* and iterate over each character up to the size of the original object. Keep in mind that the char* pointer is not a null-terminated string and may or may not contain null characters in the middle of the data, so do not process it like a C string.

Upvotes: 0

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

In the link I put in the comments, the accepted answer goes into great detail about type punning and why you can't do it in c++.

What you can do is safely inspect any object with a char* (signed or unsigned) by using reinterpret_cast.

char* ptr = reinterpret_cast<char*>(&object);
for (std::size_t x = 0; x < sizeof(object); ++x)
    std::cout << ptr[x]; //Or something less slow but this is an example

If you want to actually move the object into a char[], you should use std::memcpy.

Upvotes: 4

Related Questions