.Net SerialPort和VB6 MSComm的工作方式可能不同嗎?在這兩種情況下,我正在從緩衝區中讀取數據,並且如果將MSComm dll導入到我的.Net項目中,它們都得到了不同的字符串,它完美地工作(很明顯)。SerialPort與MSComm
有沒有人有更深的信息?
如果有幫助,這裏是我的簡單的樣品,在這兩種情況下,我發送相同的字節數組...
VB6:
Dim MSComm1 As Object
Dim ArrToSend() As Byte
Dim IncomeData As String
Set MSComm1 = CreateObject("MSCommLib.MSComm")
With MSComm1
.CommPort = 1
.PortOpen = True
End With
ReDim ArrToSend(4)
ArrToSend(0) = 179
ArrToSend(1) = 1
ArrToSend(2) = 92
ArrToSend(3) = 92
MSComm1.Output = ArrToSend
IncomeData = MSComm1.Input
C#
SerialPort _serialPort = new SerialPort();
_serialPort.Open();
Byte[] _bytesToSend = new Byte[4];
_bytesToSend[0] = 179;
_bytesToSend[1] = 1;
_bytesToSend[2] = 92;
_bytesToSend[3] = 92;
_serialPort.Write(_bytesToSend, 0, _bytesToSend.Length);
String ReadExisting = _serialPort.ReadExisting();
這兩個字符串有什麼區別?您是否檢查接收錯誤(例如奇偶校驗錯誤)?爲什麼不設置/指定COM端口參數:例如波特率,停止位和奇偶校驗? – ChrisW 2011-01-27 17:36:35
我寫了很多串口代碼,包括native和.NET,而IMO System :: IO :: Ports :: SerialPort和MSCOMM.OCX都是垃圾。他們採用功能強大且功能強大的Win32串行端口API並濫用它,迫使您陷入不良行爲。如果你想編寫健壯的代碼,你必須使用p/invoke(或者我所做的,C++/CLI包裝器)。 – 2011-01-27 18:30:03
@Ben Voigt什麼是C++/CLI包裝,如果沒有pinvoke?我認爲C++/CLI只是將遺留(非託管)C++移植到.NET中;它是否也有助於以某種方式從託管代碼訪問非託管API? – ChrisW 2011-01-27 18:45:22