Sunday, 18 August 2013

What variable type to use for parameter LPVOID lpBuffer in C++ functions WriteFile and ReadFile [migrated]

What variable type to use for parameter LPVOID lpBuffer in C++ functions
WriteFile and ReadFile [migrated]

What variable type should be used for lpBuffer of C++ ReadFile and
WriteFile functions to communicate between a Windows XP based PC and a
micro-controller based system? The PC has WinForm application in VS2010
C++/CLI. The micro-controller firmware is ANSI C.
My PC is supposed to transmit command characters (say 'S', 'C' etc)
followed by command termination character 0xd (hex for decimal 13). The
micro-controller based system would respond with 5 to 10 bytes that would
be mix of ASCII characters and hex numbers e.g. 'V' followed by 0x41 0x72
etc.
PC transmits and micro-controller receives:
TxMessage, PP1 and pTx declared as char and keeping nNumberOfBytesToWrite
as 2, makes the micro-controller receive 0x53 for 'S' followed by 0xC3
instead of 0xd.
TxMessage, PP1 and pTx declared as wchar_t and keeping
nNumberOfBytesToWrite as 2, makes the micro-controller receive 0x53 for
'S' only.
TxMessage, PP1 and pTx declared as wchar_t and keeping
nNumberOfBytesToWrite as 4, makes the micro-controller receive 0x53 for
'S' followed by 0xd correctly.
The third scheme of transmit and receive above meets my expected behavior
of a solution. But the confusion is here: Although the PC might be
transmitting 4 bytes (for two wchar types), the micro-controller receives
2 bytes 0x53 for 'S', correctly followed by 0xD.
Micro-controller transmits and PC receives:
Assuming that wchar_t is the right choice for lpBuffer, what should be my
nNumberOfBytesToRead for receiving 10 bytes from the micro-controller?
ReadFile would expect 20 bytes by virtue of wchar_t, whereas the
micro-controller would transmit 10 bytes only.
Amazingly, irrespective of declaring (RxMessage, PP2 and pRx) as wchar_t,
char or unsigned char, ReadFile receives 10 bytes from the
micro-controller (meets my expected behavior of a solution). But the issue
is that transmitting 'A' 10 times from the micro-controller, ReadFile on
the PC's end receives junk like 'S', 0x0, 0xd, 0x54, 0x29.
/// Required designer variable.
HANDLE hCommPort;
BOOL fSuccess;
array<wchar_t> ^ TxMessage;
array<unsigned char> ^ RxMessage;
TxMessage = gcnew array<wchar_t> (12);
RxMessage = gcnew array<unsigned char> (12);
{
TxMessage[0]='S';//target cmd
TxMessage[1]=0xd;//cmd termination character
DWORD dwhandled;
if (hCommPort != INVALID_HANDLE_VALUE)
{
pin_ptr<wchar_t> pp1 = &TxMessage[0];
wchar_t *pTx = pp1;
fSuccess = WriteFile(hCommPort, pTx, 4, &dwhandled, NULL);
PurgeComm(hCommPort,
PURGE_RXABORT|PURGE_TXABORT|PURGE_RXCLEAR|PURGE_TXCLEAR);
pin_ptr<unsigned char> pp2 = &RxMessage[0];
unsigned char *pRx = pp2;
fSuccess = ReadFile(hCommPort, pRx, 10, &dwhandled, NULL);
}//if IsOpen
else{
this->toolStripStatusLabel4->Text="Port Not Opened";}
}

No comments:

Post a Comment