c# 串口问题
c#串口通信中,采用win api函数ClearCommError 进行清除串口错误或者读取当前的串口的状态。
本人采用两种声明方式:
【1】
[System.Runtime.InteropServices.DllImport ("kernel32.dll")]
public static extern bool ClearCommError (
IntPtr hFile,
ref uint lpErrors,
ref COMSTAT lpStat
);
【2】
[System.Runtime.InteropServices.DllImport ("kernel32.dll")]
public static extern bool ClearCommError (
IntPtr hFile,
ref uint lpErrors,
ref IntPtr lpStat
);
对应的C#语言描述为
【1】
uint a = 0;
COMSTAT comstat2 = new COMSTAT ();
ClearCommError (myCommPtr, ref a, ref comstat2);
其中,myCommPtr已经得到串口句柄,COMSTAT 为一个结构。
【2】
uint error = 0;
IntPtr ptrComstat = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(COMSTAT)));
Win32Com.ClearCommError (myCommPtr, ref error, ref ptrComstat);
COMSTAT comstat = new COMSTAT ();
comstat = (COMSTAT)Marshal.PtrToStructure (ptrComstat, typeof (COMSTAT));
Marshal.FreeHGlobal (myCommPtr);
其中,myCommPtr已经得到串口句柄,COMSTAT 为一个结构。
现在出现问题了:【1】从comstat2 可以得到正确的串口状态,而【2】从comstat 则好像返回的是随机数据。笔者百思不得其解,请教有相关经验的高手,指点迷津,先谢谢了^_^