简体   繁体   English

static_cast不起作用

[英]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 . 我正在尝试使用static_castuint8_t*转换为Some_Type_T* ,其中Some_Type_Tstruct

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. 我已经使用类似C的演员表做了很多次。 But I though static_cast<> is safer. 但是我虽然static_cast<>更安全。

Could you give me a hint as to why this does not work? 您能否给我一个提示,为什么这行不通?

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. 实际上,继续读取内存,就像它是struct类型一样,这违反了严格的别名规则 ,从而导致未定义的行为。 Another problem is that if pData is not correctly aligned for the struct then you will get undesirable results. 另一个问题是,如果pData没有为该结构正确对齐,那么您将得到不良结果。

If your struct type is trivially copyable then you could define a struct and memcpy the data into it. 如果您的结构类型是可复制的,那么您可以定义一个结构并将数据存储到其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM