简体   繁体   English

将缓冲区数据解析为struct

[英]parsing buffer data into struct

I'm trying to create a C# wrapper for a C++ code that reads data from an HID. 我正在尝试为从HID读取数据的C ++代码创建C#包装器。 The code I have been given is pretty straight forward but not complete. 我得到的代码很简单,但是还不完整。 Data received from the device is read into the buffer as below: 从设备接收的数据按以下方式读入缓冲区:

pTmpBuf = (U8 *)calloc( InputReportByteLength, sizeof(U8));
if (ReadFile( hDevice, pTmpBuf, InputReportByteLength, &nRead, NULL))
{
memcpy(`pAppBuffer`, pTmpBuf + 1, nRead-1);
}

I want to parse the data in the pAppBuffer into the struct that is defined as follows: 我想将pAppBuffer的数据解析为如下定义的结构:

struct BAYER_CONTOUR_REPORT
{
unsigned char reportID; // HID report ID
unsigned char checkSum; // checksum for hostID + deviceID + data
unsigned char hostID // host ID assigned by communications manager
unsigned char deviceID; // device ID assigned by communications manager
unsigned char length; // length of data in buffer
unsigned char data[60]; // data send with message
};

How can this be done? 如何才能做到这一点? Any help or pointers is appreciated. 任何帮助或指针表示赞赏。

Can I simply parse the data by casting struct object onto the buffer? 我可以简单地通过将struct对象转换为缓冲区来解析数据吗?

You can do the memcpy to the struct with the incoming buffer, provided you're sure the the incoming buffer or contents are aligned to structure definition. 您可以使用传入缓冲区对struct执行memcpy ,只要您确定传入缓冲区或内容与结构定义对齐即可。

for example 例如

struct abc {
    char a;
    char b;
    char c;
    char d[2];
};

int main() {

    char arr[5] = { 'a', 'b', 'c', 'd', 'e' };
    struct abc sa;
    memcpy(&sa, arr, 5);


    return 0;
}

Here arr is incoming buffer, and with memcpy all the contents are copied appropriately. 这里arr是传入缓冲区,使用memcpy可以适当地复制所有内容。

Similarly, in your code you can do the following 同样,在您的代码中,您可以执行以下操作

struct BAYER_CONTOUR_REPORT bcr;
memcpy(&bcr, pAppBuffer, sizeof(struct BAYER_CONTOUR_REPORT))

Again, please mind the caveats that you need to be absolutely sure that size of struct struct BAYER_CONTOUR_REPORT and pAppBuffer is exactly same and the information is aligned to your structure 再次提醒您,请注意以下struct struct BAYER_CONTOUR_REPORT必须绝对确保struct struct BAYER_CONTOUR_REPORTpAppBuffer大小完全相同,并且信息与您的结构对齐

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

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