gpt4 book ai didi

c++ - 读取串行 COM 端口上的字符串

转载 作者:行者123 更新时间:2023-11-28 06:44:24 25 4
gpt4 key购买 nike

我正在研究串行 COM 端口 ANSI 字符读取项目。我可以处理发送数据,但无法处理接收数据。提供任何帮助。

这是读取函数:

BOOL ReadString(char *outstring)
{
int *length;
*length = sizeof(int);
BYTE data;
BYTE dataout[8192]={0};
int index = 0;
while(ReadByte(data)== TRUE)
{
dataout[index++] = data;
}
memcpy(outstring, dataout, index);
*length = index;
return TRUE;
}

Main.cpp 是:

int main(void)
{
// Configs
hPort = ConfigureSerialPort("COM1");
if(hPort == NULL)
{
printf("Com port configuration failed\n");
return -1;
}


char* cPTR;
for(;;)
{
ReadString(cPTR);
if(cPTR!=NULL) cout << "Scanned Data: " << cPTR << endl;
else cout << "No data recieved." << endl;
}
ClosePort();
return 0;
}

最佳答案

有多个错误:使用 C 字符串而不是 std::string,没有绑定(bind)检查,等等:

BOOL ReadString(char *outstring)
{
int *length; // !!!! length is not initialized, it may point to any address
*length = sizeof(int);

BYTE data;
BYTE dataout[8192]={0};
int index = 0;

while(ReadByte(data)== TRUE) // !!!! No bound check. What if index will become more than 8192?
{
dataout[index++] = data;
}
memcpy(outstring, dataout, index);
*length = index; // Hmm, length is not static it is automatic variable and will not keep the index between the calls

return TRUE;
}

主要内容:

int main(void)
{
// Configs
hPort = ConfigureSerialPort("COM1");
if(hPort == NULL)
{
printf("Com port configuration failed\n");
return -1;
}


char* cPTR; // !!!! Not initialized, points to any place in memory
for(;;)
{
ReadString(cPTR); // !!!! cPTR not allocated, you pass the pointer to somwhere

if(cPTR!=NULL)
cout << "Scanned Data: " << cPTR << endl;
else
cout << "No data recieved." << endl;
}
ClosePort();
return 0;
}

我对读取字符串函数的建议:

void ReadString(
std::string& result,
std::size_t& size)
{
result.clear(); // If you need to keep track - don't clear

BYTE byteIn;
while (ReadByte(byteIn))
{
result.append(byteIn); // Maybe static_cast<char>(byteIn) required for BYTE to char
size++;
}
}

现在我们可以将 main 重写为:

std::string buffer;
std::size_t length = 0;

while (true)
{
ReadString(buffer, length);

if(buffer.size())
cout << "Scanned Data: " << buffer << endl;
else
cout << "No data recieved." << endl;

// Some condition to break the cycle after 1Mb
if (length > 1024 * 1024)
break;
}

关于c++ - 读取串行 COM 端口上的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25280489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com