C#调用C++库,进行串口通信

1、添加C++接口实现,将dll放置在运行路径下。

dll文件下载:https://files.cnblogs.com/files/ZM191018/SerialPortLib.7z?t=1721281910&download=true

     [DllImport("SerialPortLib.dll",CharSet=CharSet.Unicode,CallingConvention =CallingConvention.StdCall)]
        static extern int openDevice(string COMName, int dwBaud, string sframe, ref UIntPtr hCom);

        [DllImport("SerialPortLib.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
        static extern int closeDevice(UIntPtr hCom);

        [DllImport("SerialPortLib.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
        static extern int startComminication(RECEIVE_CALLBACK receive, byte[] sendData, int dlen, UIntPtr hCom);

2、调用接口打开串口设备

      UIntPtr hCom2 = UIntPtr.Zero;
        private void button3_Click(object sender, EventArgs e)
        {
            string strComName = comboBox1.Text;
            int iBaud = Convert.ToInt32(comboBox2.Text);
            string strFrame = comboBox3.Text;
            try
            {
                int iret = openDevice(strComName, iBaud, strFrame, ref hCom2);
                if (iret == 0)
                {
                    button3.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

3、调用接口将委托作为参数传入,当读取到数据时,进行回调

      public delegate int RECEIVE_CALLBACK(IntPtr recvData, int dlen);
        private void button5_Click(object sender, EventArgs e)
        {
            string sendStr = richTextBox1.Text;
            byte[] sendArr=StringToHexByteArray(sendStr);

            int iret=startComminication(new RECEIVE_CALLBACK(RecvCallBack), sendArr,sendArr.Length, hCom2);
        }

        public int RecvCallBack(IntPtr recvData, int dlen)
        {
            if (recvData != null && dlen > 0)
            {
                byte[] data = new byte[dlen];
                Marshal.Copy(recvData, data, 0, dlen);
                string str = BitConverter.ToString(data, 0, (int)dlen).Replace("-", "");
                this.Invoke((EventHandler)delegate
                {
                    richTextBox2.AppendText(str + "\n");
                    richTextBox2.SelectionStart = richTextBox2.Text.Length;
                    richTextBox2.ScrollToCaret();

                });
                return 0;
            }
            else
            {
                return -1;
            }
        }

4、关闭串口

private void button4_Click(object sender, EventArgs e)
        {
            int iret = closeDevice(hCom2);
            if (iret == 0)
            {
                hCom2 = UIntPtr.Zero;
                button3.Enabled = true;
            }

        }

5、可能用到的方法

     public static byte[] StringToHexByteArray(string hex)
        {
            if (hex.Length % 2 == 1)
                return null;
            int len = hex.Length >> 1;
            byte[] arr = new byte[len];

            for (int i = 0; i < len; ++i)
            {
                arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
            }

            return arr;
        }

        public static int GetHexVal(char hex)
        {
            int val = (int)hex;
            //For uppercase A-F letters:
            // return val - (val < 58 ? 48 : 55);
            //For lowercase a-f letters:
            //return val - (val < 58 ? 48 : 87);
            //Or the two combined, but a bit slower:
            return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
        }

 6、效果

 

posted @ 2024-07-18 11:08  !>Mon<!  阅读(4)  评论(0编辑  收藏  举报