所以我有如下内容:
在我的 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/