User Tools

Site Tools

blog:2023-05-18_c_copy_array



2023-05-18 C#: Duplicate Byte Array

  • There are two byte arrays which are populated with different values.
  • byte[] array1 = new byte[5];
    byte[] array2 = new byte[5];
  • We need array1 to get exactly the same values as array2, by using
    array1 = array2;
    , it is just set references.

Solution

  • One solution is
    byte[] array1 = new byte[5];
    // copy the values to array1
    byte[] array2 = array1.ToArray();
  • We also used in out CAN message receive routine as follows:
            private int Task_CanBusWriteReadMessage ()
            {
                // 傳送一個Message,並等待回傳的回應訊息
                // 將 Global.VAR_CanMsgSend Message傳送出去
                // 等待回應,存在 Global.VAR_CanMsgReceived
                // Return Value:
                //   =1, 成功收到回應
                //   =0, 沒有收到回應,Timeout
                
                Task_TransmitCanMessage(); // 傳送Message
    
                TimeoutTimer1.StartTimer(1000); // Timeout 1秒 
                // 開啟 SuperTimer的計時功能 --->
                TimeoutTimer1.Enable = true;
                Global.VAR_CanMessageReceived = false; // 先設為沒收到
                while (true)
                {
                    Application.DoEvents(); // 讓應用程式可以處理其他事件
                    if (Global.VAR_CanMessageReceived)
                    {
                        // 收到CAN Message 時,跳出迴圈
                        // Console.WriteLine("Can Message Received..");
                        break;
                    }
                    // 若是Timeout時,跳出迴圈
                    if (TimeoutTimer1.TimerExpired() == true)
                    {
                        // MessageBox.Show("Receive timeout", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        Console.WriteLine("Timeout.." + TimeoutTimer1.gTickCount.ToString());
                        break;
                    }
                }
    
                // <--- Disable SuperTimer的計時功能;避免佔用 CPU 計算資源
                TimeoutTimer1.Enable = false;
    
                if (!Global.VAR_CanMessageReceived) 
                {
                    // 沒有收到,而是Timeout的話
                    return (0);
                }
                DEBUG_DumpCanReceivedMessage();
                // 原本只是把pointer指過去而已, 因此Array.Reverse會影響原本的Array
                Global.VAR_CanMsgDataReversed = Global.VAR_CanMsgReceived.DATA.ToArray(); // 將收到的CAN Message拿取出來
                Array.Reverse(Global.VAR_CanMsgDataReversed); // 將Array Reverse order
                // Console.WriteLine ("Received Msg: " + Global.VAR_CanMsgReceived.ID.ToString("X3") + ":");
                return (1);
            }

TAGS

  • 79 person(s) visited this page until now.

Permalink blog/2023-05-18_c_copy_array.txt · Last modified: 2023/05/18 11:16 by jethro

oeffentlich