Accessing structure members with a pointer

放肆的年华 提交于 2019-12-24 02:57:23

问题


I'm trying to translate the following code from C++ to C#

`

struct tPacket
{
WORD size;
WORD opcode;
BYTE securityCount;
BYTE securityCRC;
}

...

static char data[8192] = {0};
tPacket * packet = (tPacket *)data;`

so far I've come up with:

C#

public struct tPacket
{
public ushort size;
public ushort opcode;
public byte securityCount;
public byte securityCRC;
}     

public static byte[] data = new byte[1024];
tPacket packet = new tPacket();
packet = (tPacket *)data;

However,I get an error "Cannot convert type 'byte[]' to 'MyNameSpace.tPacket*"

The whole code is used to put a received packet buffer(data) into a structure then directly access the structure members. Any help will be appreciated! Thanks in advance.


回答1:


Here's a link that might help:

http://varjabedian.net/archive/2008/07/29/casting-a-byte-array-into-structures-in-c.aspx



来源:https://stackoverflow.com/questions/676207/accessing-structure-members-with-a-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!