简体   繁体   English

将void *强制转换为struct *

[英]Cast void* to struct*

I have this struct: 我有这个结构:

typedef struct
{
    UINT8 a;
    UINT8 len;
    BYTE *data;
} MyStruct;

and this binary array [0x00, 0x03, 0x08, 0x09, 0x0a] which is assigned to a void* variable "BINDATA". 并将此二进制数组[0x00、0x03、0x08、0x09、0x0a]分配给void *变量“ BINDATA”。

How can I cast BINDATA to MyStruct and be able to access its "data" field? 如何将BINDATA强制转换为MyStruct并能够访问其“数据”字段?

I tried: 我试过了:

MyStruct *myStruct = (MyStruct*) BINDATA;

After that I was able to access: 之后,我可以访问:

myStruct->a; //gave me 0x00
myStruct->len; //gave me 0x03

But I could not access 但我无法访问

myStruct->data;

without memory access violation. 没有内存访问冲突。 I guess this is because "data" address pointer gets set to 0x08 and not its value. 我猜这是因为“数据”地址指针被设置为0x08而不是其值。

Instead of BYTE *data you should use BYTE data[0] or (if your compiler doesn't like this) BYTE data[1] . 代替BYTE *data您应该使用BYTE data[0]或(如果编译器不喜欢) BYTE data[1] The difference between pointer and array here is crucial - array is "data that is right here" while pointer is "data somewhere else" which is not your case. 这里的指针和数组之间的区别很关键-数组是“此处的数据”,而指针是“其他位置的数据”,这不是您的情况。

Something like this may work in c++: 这样的事情可能在c ++中起作用:

UINT* a1 = &myStruct->len;
UINT* a2 = ++a1;

Then cast a2 to whatever you want. 然后将a2投射到任何您想要的位置。 Be aware of the size and the type of your data. 请注意数据的大小和类型。

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

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