如何在C++中传递对打开串行端口的引用



我需要将打开串行端口的引用传递给C++中的函数。现在我正在打开和关闭函数内的串行端口,这当然是一种糟糕且低效的方式:

int main()
{
    myFunc();
}

myFunc 在单独的库中定义:

int myFunc(void)
{
   Serial* SP = new Serial("\\.\COM6");              
   if (!SP->IsConnected()) {
       cout << "Arduino is  not connected" << endl;
       return -1;
   }
   // do something
   SP->~Serial();
}

如果我尝试在 main 中打开端口并将对 SP 的引用传递给函数,它会给我一个错误:

int main()
{
    Serial* SP = new Serial("\\.\COM6");                 
    if (!SP->IsConnected()) {
       cout << "Device is  not connected" << endl;
       return -1;
    }
    myFunc(SP);
    SP->~Serial();
}
int myFunc(Serial* SP)
{
   // do something
}

我尝试了函数定义的不同变体,例如 int myFunc(Serial *SP(或 int myFunc(Serial SP(但注意到工作。任何帮助将不胜感激

您的代码存在几个问题:

  • 您没有将任何参数传递给 myFunc
  • 显式调用析构函数但不释放内存
  • 您可以在堆上创建对象,而无需这样做。

下面我试图解决代码中的一些问题:

int myFunc(Serial& SP)
{
    // do something
}
int main()
{
    Serial SP("\\.\COM6");                 
    if (!SP.IsConnected()) {
       cout << "Device is  not connected" << endl;
       return -1;
    }
    myFunc(SP);
}

这是我更新的完整代码,现在可以工作了。我还需要在.h文件中 #include"SerialClass.h"。非常感谢所有帮助过的人!

#include "mylib.h"
#include "SerialClass.h"
int main()
{
    Serial SP("\\.\COM6");                 
    if (!SP.IsConnected()) {
       cout << "Device is  not connected" << endl;
       return -1;
    }
    myFunc(SP);
    return 1;
}

在 Mylib 中.cpp

#include "SerialClass.h"
int myFunc(Serial& SP)
{
    // do something
    SP.WriteData(6, 1);
    return 1;
}

在 Mylib.h 中

#pragma once
#ifndef _MYLIB_H_
#define _MYLIB_H_
#include "SerialClass.h"   
int myFunc(Serial& SP);
#endif

最新更新