【问题标题】:Passing HANDLE as an argument when opening a com port in C/C++ in Windows在 Windows 的 C/C++ 中打开 com 端口时将 HANDLE 作为参数传递
【发布时间】:2015-01-29 03:00:30
【问题描述】:

所以我有如下内容:

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

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

任何帮助将不胜感激!

【问题讨论】:

  • "// 这会产生良好的结果" - 如果您定义了 STRICT(您应该这样做),则不会。 hCom = CreateFile(...) 其中hComHANDLE* 甚至不应该编译CreateFile 返回 HANDLE,而不是 HANDLE*

标签: c windows serial-port


【解决方案1】:

这不是真正的 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

【讨论】:

    【解决方案2】:

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

    HANDLE *hCom;
    hCom = CreateFile(......)
    success = openport(hCom);
    ReadFile(hCom......)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2013-10-19
      • 2012-07-27
      • 1970-01-01
      • 2015-05-05
      相关资源
      最近更新 更多