将缓冲区数据解析为struct [英] parsing buffer data into struct

查看:106
本文介绍了将缓冲区数据解析为struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为从HID读取数据的C ++代码创建C#包装器.我得到的代码很简单,但是还不完整.从设备接收到的数据按如下方式读入缓冲区:

I'm trying to create a C# wrapper for a C++ code that reads data from an HID. 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);
}

我想将pAppBuffer中的数据解析为如下定义的结构:

I want to parse the data in the pAppBuffer into the struct that is defined as follows:

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.

推荐答案

我可以简单地通过将struct对象转换为缓冲区来解析数据吗?

Can I simply parse the data by casting struct object onto the buffer?

只要确定传入缓冲区或内容与结构定义对齐,就可以对传入缓冲区进行memcpystruct的操作.

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 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;
}

这里arr是传入缓冲区,并且使用memcpy适当地复制了所有内容.

Here arr is incoming buffer, and with memcpy all the contents are copied appropriately.

类似地,在您的代码中,您可以执行以下操作

Similarly, in your code you can do the following

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

同样,请注意以下几点警告:您必须绝对确保struct struct BAYER_CONTOUR_REPORTpAppBuffer的大小完全相同,并且信息与您的结构保持一致

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆