JMR
JMR

Reputation: 765

C++ - Convert struct to char

I'm need to convert this structure

 typedef struct zidrecord2 {
        char version;  
        char flags;     
        char filler1;   
        char filler2;   
        unsigned char identifier[IDENTIFIER_LEN]; 
        unsigned char rs1Interval[TIME_LENGTH];   
        unsigned char rs1Data[RS_LENGTH];         
        unsigned char rs2Interval[TIME_LENGTH]; 
        unsigned char rs2Data[RS_LENGTH];        
        unsigned char mitmKey[RS_LENGTH];      
}

to a char * or to another object that allows to roll back again to the object I try this:

zidrecord2_t* amostra =  zidRecord->getRecordData();

const char *recordData = reinterpret_cast<const char*>(zidRecord->getRecordData());
    __android_log_print(ANDROID_LOG_INFO, "MyTag", "The value is %s",recordData);
    amostra = reinterpret_cast<zidrecord2_t*>(recordData);
    __android_log_print(ANDROID_LOG_INFO, "MyTag", "The value is %s",recordData);

But I get the following error:

error: reinterpret_cast from type 'const char*' to type 'zidrecord2_t* {aka zidrecord2*}' casts away qualifiers
     amostra = reinterpret_cast<zidrecord2_t*>(recordData);

How can I pass this problem? or implement in another way?

Upvotes: 0

Views: 841

Answers (2)

Kieran Chandler
Kieran Chandler

Reputation: 188

You can add a user-defined conversion operator:

So your code might look like the following:

typedef struct zidrecord2 {
    char version;  
    char flags;     
    char filler1;   
    char filler2;   
    unsigned char identifier[IDENTIFIER_LEN]; 
    unsigned char rs1Interval[TIME_LENGTH];   
    unsigned char rs1Data[RS_LENGTH];         
    unsigned char rs2Interval[TIME_LENGTH]; 
    unsigned char rs2Data[RS_LENGTH];        
    unsigned char mitmKey[RS_LENGTH];

    operator char*() const { return ConvertToCharPointerHere();
}

Upvotes: 0

George Sovetov
George Sovetov

Reputation: 5218

amostra = reinterpret_cast<const zidrecord2_t*>(recordData);

Cast from const to const.

If you want to cast const away, use non-const pointers from the beginning.

Upvotes: 2

Related Questions