Search code examples
c#labview

How to convert back a flattened string to DBL array?


I am trying to send a flatteded DBl array from labview to c# through tcp. i am receiving the flattened string in c#. i dont know how to convert them back to DBL array?

This is my code in C#:

{

    private TcpClient socketConnection;
    private Thread clientReceiveThread;


    void Start()
    {
        ConnectToTcpServer();
    }

    void Update()
    {

    }


    private void ConnectToTcpServer()
    {
        try
        {
            clientReceiveThread = new Thread(new ThreadStart(ListenForData));
            clientReceiveThread.IsBackground = true;
            clientReceiveThread.Start();
        }
        catch (Exception e)
        {
            Debug.Log("On client connect exception " + e);
        }
    }


    private void ListenForData()
    {
        try
        {
            socketConnection = new TcpClient("localhost", 5333);
            Byte[] bytes = new Byte[4000];
            while (true)
            {

                using (NetworkStream stream = socketConnection.GetStream())
                {
                    int length;

                    while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        Debug.Log(bytes.Length);
                        var incomingData = new byte[length];
                        Array.Copy(bytes, 0, incomingData, 0, length);
                        // Convert byte array to string message.                        
                        string serverMessage = Encoding.ASCII.GetString(incomingData);
                        Debug.Log("server message received as: " + serverMessage);
                        Debug.Log(serverMessage.Length);


                    }
                }
            }
        }
        catch (SocketException socketException)
        {
            Debug.Log("Socket exception: " + socketException);
        }
    }


}

This is my labview code:

This is my labview output: (Float array and flattened string)

This is the output in C#:


Solution

  • Since you wired FALSE to the "prepend array or string size", the only data in the buffer is the flattened doubles themselves. But you need to explicitly set "little endian" in order to talk to C#.

    If you make that change in the G code, then this should work:

    double[] dblArray = (double[])Array.CreateInstance(typeof(System.Double), length / 8); 
    // I'm not sure if you need the cast or not.
    

    You have the constant "4000" in your code. I would change that to a declared constant and put a comment next to it that says, "Make sure this is a multiple of 8 (number of bytes in double data type)."