我正在撰寫一個小程式來與 USB 到 UART 橋(CP210x)進行通信。
該程式相當簡單,但是當我減小以下出站訊息陣列的大小(wm_size < 25)時,我會遇到分段錯誤。產生分段錯誤的代碼如下所示:
HANDLE prog_com_port;
prog_com_port = CreateFileA("\\\\.\\COM4",
GENERIC_READ | GENERIC_WRITE, //Request Read and Write Acess
0, //Block others from sharing Acess
NULL, //Disable Security features
OPEN_EXISTING, //Only open existing device
FILE_ATTRIBUTE_NORMAL, //Used to set atributes and flags
NULL);
//Handle to
if(prog_com_port == INVALID_HANDLE_VALUE)
{
printf("Opening COM port failed - INVALID_HANDLE_VALUE\n");
CloseHandle(prog_com_port);
return 1;
}
else
printf("COM port was opened successfully \n");
SetupCommState(prog_com_port);
Sleep(2);
#define wm_size 25
int messageLength = 2;
char W_message[wm_size] = {0x01,0x01};
long unsigned int * bytes_sent;
BOOL Status;
Status = WriteFile(prog_com_port, // Handle to the Serial port
&W_message, // Pointer to message buffer
messageLength, // No of bytes to write
bytes_sent, // Pointer to number of bytes written
NULL);
if(!Status)
{
printf("Failed to write to COM port - 0x00 \n");
CloseHandle(prog_com_port);
return 2;
}
CloseHandle(prog_com_port);
我的邏輯告訴我設定 wm_size = 2 就足夠了,但顯然這是錯誤的。有人能告訴我為什么嗎?
我玩弄了 wm_size 的大小,并在實驗上發現 25 解決了這個問題。
uj5u.com熱心網友回復:
wm_size = 2 夠了,問題出在別處:bytes_sent是一個無處指向的指標。
您的“修復”沒有解決任何問題。您遇到了未定義的行為(包括顯然作業正常)。
你想要這個(所有評論都是我的):
DWORD messageLength = 2; // use DWORD
DWORD bytes_sent; // use DWORD
char W_message[] = {0x01,0x01}; // you don't need wm_size
Status = WriteFile(prog_com_port,
W_message, // remove &, W_message decays into a pointer
messageLength,
&bytes_sent, // put &, you need a pointer here
NULL);
甚至更好:你不需要messageLength:
Status = WriteFile(prog_com_port,
W_message, // remove &
sizeof(W_message), // assuming W_message contains chars
&bytes_sent, // put &
NULL);
// now bytes_sent contains the number of bytes sent (hopefully 2),
// providing WriteFile succeeded (Status is TRUE)
強烈建議使用DWORD,因此傳遞給的引數型別WriteFile與宣告(和檔案)實際匹配。另請注意,LPDWORD在所有 Microsoft 檔案和頭檔案中,與DWORD*.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/521566.html
標籤:C视窗温纳皮
