重写串口通信从c++到c#
本文关键字:c++ 串口 通信 重写 | 更新日期: 2023-09-27 18:15:18
我想知道我是否正确地将这段建立串口通信的c++代码映射到c#。
void some func(...)
{
*hDev = CreateFile(PortNameUNC, GENERIC_READ|GENERIC_WRITE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(*hDev == INVALID_HANDLE_VALUE) return false ;
DCB *dcb = new DCB ;
memset(dcb, 0x00, sizeof(DCB)) ;
dcb->DCBlength = sizeof(DCB);
dcb->BaudRate = BaudRate;
dcb->Parity = Parity;
dcb->StopBits = StopBits;
dcb->ByteSize = ByteSize;
dcb->fBinary = TRUE;
dcb->fDsrSensitivity = 0;
dcb->fDtrControl = (DTR ? DTR_CONTROL_ENABLE : DTR_CONTROL_DISABLE) ;
dcb->fRtsControl = (RTS ? RTS_CONTROL_ENABLE : RTS_CONTROL_DISABLE) ;
dcb->fOutxCtsFlow = (CTS ? 1 : 0) ;
dcb->fOutxDsrFlow = (DSR ? 1 : 0) ;
dcb->fOutX = (XonnXoff ? 1 : 0) ;
dcb->fInX = 0 ;
if(!SetCommState(*hDev, dcb))
{
delete dcb ;
CloseHandle(*hDev) ;
*hDev = INVALID_HANDLE_VALUE ;
return false;
}
if(!SetTimeOut(readTimeOut, ReadIntervalTimeout) || !Reset())
{
CloseHandle(*hDev) ;
*hDev = INVALID_HANDLE_VALUE ;
return false;
}
}
bool serial::SetTimeOut(DWORD readTimeOut, DWORD ReadIntervalTimeout)
{
COMMTIMEOUTS *timeouts = new COMMTIMEOUTS ;
memset(timeouts, 0, sizeof(COMMTIMEOUTS)) ;
timeouts->ReadIntervalTimeout = ReadIntervalTimeout ;
timeouts->ReadTotalTimeoutMultiplier = 5 ;
timeouts->ReadTotalTimeoutConstant = readTimeOut ; //...
timeouts->WriteTotalTimeoutConstant = 0 ; //
timeouts->WriteTotalTimeoutMultiplier = 2*BaudRate/8 ;
const bool ret = SetCommTimeouts(*hDev, timeouts) != FALSE ;
delete timeouts ;
m_currentTimeOut = readTimeOut ;
return ret ;
}
这是我的c#映射:
public SerialPortHASP(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, bool dtr, bool rts, bool xonxoff)
{
m_port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
// Just store parameters user entered
m_portName = portName;
m_baudRate = baudRate;
m_parity = parity;
m_dataBits = dataBits;
m_stopBits = stopBits;
m_xonxoff = xonxoff;
m_dtr = dtr;
m_rts = rts;
// Set XonXoff if set
if (xonxoff)
m_port.Handshake = Handshake.XOnXOff;
// Set DTR/RTS
m_port.DtrEnable = dtr;
m_port.RtsEnable = rts;
m_port.ReadTimeout = 500; // or some other values
m_port.WriteTimeout = 500;
// Open the port for communications
m_port.Open();
}
我将需要实现一些其他读写操作(根据协议),直到我可以测试我的映射是否正确,所以这就是为什么我要仔细检查我是否采取了正确的方法在上面的代码映射到c# ?或者我应该使用PInvoke调用这条路线吗?还是继续尝试我现在的方法?由于
p。你可以看到,我无法复制c++调用的所有参数允许创建
我将在初始化中添加:
m_port.DataReceived += _serial_DataReceived;
事件从端口获取数据。这是异步工作所需要的。
和
void _serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int _len = _serial.BytesToRead;
byte[] _out = new byte[_len];
_serial.Read(_out, 0, _len);
}