c - 在 Windows 的 C/C++ 中打开 com 端口时将 HANDLE 作为参数传递

标签 c windows serial-port

所以我有如下内容:

在我的 main.c 中

HANDLE *hCom;
success = openport(hCom);
ReadFile(hCom......)   // This Produces Garbled Results

openport() 函数:

 int openport(HANDLE *hCom)
 {
     hCom = CreateFile(......)
     ReadFile(hCom......)   // This Produces Good Results
     return 0;
 }

当我在我的 openport() 函数中读取命令时,一切正常,但如果我在我的 main.c 中使用 hCom,我会得到垃圾。

我的问题是,我做错了什么/遗漏了什么?

如有任何帮助,我们将不胜感激!

最佳答案

这不是真正的 Windows 问题,而是一个基本的 C 问题:您误用了指针。您传递给 ReadFile 的值从未被初始化,它是随机垃圾。

代码应该是这样的:

HANDLE hCom;   // declare a HANDLE (not a pointer to one)
success = openport(&hCom);   // pass the function a pointer to the HANDLE
ReadFile(hCom......);   // use the HANDLE

int openport(HANDLE *hCom)   // We receive a pointer
{
  *hCom = CreateFile(......)   // Write to the variable being pointed to
  ReadFile(*hCom......)
  return 0;
}

或者,等价地(虽然不那么优雅):

HANDLE *hCom;   // declare a pointer to a HANDLE
hCom = malloc(sizeof(HANDLE)); // allocate space for it
success = openport(hCom);   // pass the function the pointer
ReadFile(*hCom......);   // use the pointer

关于c - 在 Windows 的 C/C++ 中打开 com 端口时将 HANDLE 作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28206311/

相关文章:

c - C语言如何判断标识符是否为字符?

c - Malloc 字符串数组 - C

c - Readline 完成问题

windows - 如何访问 Windows 共享上的 git 存储库?

Linux串口应用程序不工作

尝试访问通信端口时 C# 访问被拒绝?

bash - Docker容器看不到串口设备

c - 将消息翻译为 B1FF 语言时出现问题

linux - 二进制数如何表示为字符

python - 如何配置Bitvise SSH Server,使进程在前端运行