0
我的問題是,當發送消息L「第二行」給我的應用程序讀取串口時,我收到「第二個L ine」,但是在putty中我收到了「Second行「我認爲這是因爲wchar_t編碼爲16位,所以我在每個字母之間都有一個00。但仍然不知道如何解決這個問題,我對這些東西都是新的,所以這有點令人困惑。通過串口發送wchar_t消息
我不確定是否需要在我的應用程序中將字節大小設置爲16?
我想發送LPCWSTR LogpszMessage,因爲我正在從應用程序發送一些日誌消息。這是另一個代碼,在這裏工作必須在那裏工作。
膩子配置是8位,這就是我發送的;
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
typedef _Null_terminated_ CONST WCHAR *LPCWSTR, *PCWSTR;
int main()
{
LPCWSTR LogpszMessage = L"Second line";
char bytes_to_send[] = "test1 y test2";
// Declare variables and structures
HANDLE hSerial;
DCB dcbSerialParams = { 0 };
COMMTIMEOUTS timeouts = { 0 };
// Open the highest available serial port number
fprintf(stderr, "Opening serial port...");
hSerial = CreateFile(
L"\\\\.\\COM24", GENERIC_READ | GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hSerial == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "Error\n");
return 1;
}
else fprintf(stderr, "OK\n");
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (GetCommState(hSerial, &dcbSerialParams) == 0)
{
fprintf(stderr, "Error getting device state\n");
CloseHandle(hSerial);
return 1;
}
dcbSerialParams.BaudRate = CBR_115200;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if (SetCommState(hSerial, &dcbSerialParams) == 0)
{
fprintf(stderr, "Error setting device parameters\n");
CloseHandle(hSerial);
return 1;
}
// Set COM port timeout settings
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (SetCommTimeouts(hSerial, &timeouts) == 0)
{
fprintf(stderr, "Error setting timeouts\n");
CloseHandle(hSerial);
return 1;
}
// Send specified text (remaining command line arguments)
DWORD bytes_written, total_bytes_written = 0;
fprintf(stderr, "Sending bytes...");
/*if (!WriteFile(hSerial, bytes_to_send, sizeof(bytes_to_send), &bytes_written, NULL))
{
fprintf(stderr, "Error\n");
CloseHandle(hSerial);
return 1;
}*/
if (!WriteFile(hSerial, LogpszMessage, wcslen(LogpszMessage) * sizeof(wchar_t), &bytes_written, NULL))
{
fprintf(stderr, "Error\n");
CloseHandle(hSerial);
return 1;
}
fprintf(stderr, "%d bytes written\n", bytes_written);
// Close serial port
fprintf(stderr, "Closing serial port...");
if (CloseHandle(hSerial) == 0)
{
fprintf(stderr, "Error\n");
return 1;
}
fprintf(stderr, "OK\n");
getchar();
// exit normally
return 0;
}
在此先感謝。
膩子只是簡單地打印它收到的字節的可顯示的文本,並不知道你發送的任何utf16。二進制零是特殊的,它沒有等價的字符。所以你根本看不到它,它只是*看起來像它正在正常工作。檢查[this superuser.com問題](https://superuser.com/questions/150202/display-hex-in-putty-for-serial)。如果您不希望這些二進制零出現在日誌文件中,那麼您需要通過爲您傳輸的文本選擇一種編碼來超前。考慮具有CP_ACP或CP_UTF8的WideCharToMultiByte()。 –
謝謝@HansPassantM讓我閱讀關於WideCharToMultiByte()並嘗試它。我完全理解你的答案。 – COCerv