问题
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);
}
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.
回答1:
Can I simply parse the data by casting struct object onto the buffer?
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.
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.
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
来源:https://stackoverflow.com/questions/41671618/parsing-buffer-data-into-struct