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

Passing HANDLE as an argument when opening a com port in C/C++ in Windows

所以我有如下内容:

在我的 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,我会得到垃圾。

我的问题是,我在做什么wrong/missing?

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

也许 hCom = CreateFile(......) 会创建 HANDLE 或 ..,您可以在 main.c.

中使用 hCom = CreateFile(......)
HANDLE *hCom;
hCom = CreateFile(......)
success = openport(hCom);
ReadFile(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