Typecasting struct to char* in C++ without a lot of fluff

Want to cast from a struct to a character string? Seen all those posts out there suggesting that reinterpret_cast will work, but is unsafe? Yeah, I tried it. Yeah, it's unsafe.

What about the ones saying you could just malloc()? Well, my own personal mantra says that direct memory manipulation is also rather unsafe if you don't count right or are not careful with stack memory and such. I have avoided malloc() like I have learned to avoid reinterpret_cast.

But just today I discovered a most elegant solution:

struct newStruct { //33 total bytes long
    int dw0;
    uint_16 s0, s1, s2, s3;
    float f0, f1, f2, f3;
    char b0;
    int i0;

void byteOperation(char *p) {
    // Treat input parameter "p" like a big character array and do things one byte at a time!!

newStruct v;
newStruct w[1];

byteOperation((char*)v); // Compiler error: Cannot cast from 'newStruct' to 'char *'
byteOperation((char*)w); // Will just work.

No comments :

Post a Comment

Comment loud, comment often. But comment on the content!

All comments are filtered through to my email, so your spam will never make it. Unless, of course, you wanted to try injection attacks into my email, which would probably not happen since Blogger just tells me that a comment is awaiting moderation and doesn't bother to tell me what it says. I trust Blogger like that..