1

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?

JeJo
  • 30,635
  • 6
  • 49
  • 88
JuliusCaesar
  • 341
  • 3
  • 14
  • 2
    Because that's not a cast `static_cast` performs. You want `reinterpret_cast`. Check out the relevant docs. – Baum mit Augen May 13 '18 at 21:23
  • 1
    The only standard-compliant way is to `memcpy`. If you know that `reinterpret_cast` works on your platform and with your compilers, you can use that. It's what it was meant for, but not all current compilers can be trusted to do what's reasonable. – Cheers and hth. - Alf May 13 '18 at 21:27
  • `static_cast` only converts between related types. Roughly, if there is an implicit conversion one way, then `static_cast` can do the opposite way. Main exception: it can't convert a pointer to array type. – Cheers and hth. - Alf May 13 '18 at 21:29
  • 1
    You are right that `static_cast` is safer - it's telling you that what you are trying to do is bad/dangerous (as it's breaking *strict aliasing*) – UnholySheep May 13 '18 at 21:34
  • @Cheersandhth.-Alf Well `static_cast` can convert to and from `void*`, I find it a stretch to call that “related” to any type. Furthermore, performing the mapping `SomeType*` → `unsigned char*` → `SomeType*` via `reinterpret_cast` is well-defined. This might fit OP’s use-case. – Konrad Rudolph May 13 '18 at 21:55
  • @KonradRudolph: With C++03 you could define the informal "related" for this context as "there exists an implicit conversion at least one way between the types". My qualification "roughly" then only concerned casting to `void` (not the pointer type). With C++11 and later `static_cast` can cast between some more types that are not related via implicit conversions, namely `enum class` types. I think you'll agree that these types are related, though just not via the simple definition one could use for C++03. – Cheers and hth. - Alf May 13 '18 at 22:13

1 Answers1

3

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.

M.M
  • 138,810
  • 21
  • 208
  • 365