JuliusCaesar
JuliusCaesar

Reputation: 351

static_cast does not work

I'm trying to use static_cast to convert uint8_t* to Some_Type_T* where Some_Type_T is a struct.

SomeType_T* pTarget = static_cast<SomeType_T*>(pData)

That gives me an error

invalid static_cast from type 'uint8_t [1000] {aka unsigned char [1000]}' to type 'Some_Type_T*'

Basically what I'm trying to achieve is to map a buffer (byte array) to some structure.

I have done this many times with the C-like cast. But I though static_cast<> is safer.

Could you give me a hint as to why this does not work?

Upvotes: 1

Views: 3984

Answers (1)

M.M
M.M

Reputation: 141658

The name of the cast would be:

SomeType_T* pTarget = reinterpret_cast<SomeType_T*>(pData);

because you intend to reinterpret a byte array as another object type.

Actually going ahead and reading the memory as if it were the struct type violates the strict aliasing rule, causing undefined behaviour. Another problem is that if pData is not correctly aligned for the struct then you will get undesirable results.

If your struct type is trivially copyable then you could define a struct and memcpy the data into it.

Upvotes: 3

Related Questions