Hi Group,
I am trying without much luck to pack messages into a byte buffer
using get and set accessors.
I have attached a simplified example of what I am trying to do using
byte variables.
(My real data is not byte variables.)
I wish to be able to populate a field in the message header and then
include this in a
init message, and finally once all the message is transfered to the
byte buffer populate
the message header length.
However I alway get zero for my message header length when I write to
the console.
I am confused I think with the get and set accessor.
Could anyone suggest where I have gone wrong.
Mark
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
msgHdr msgHeader = new msgHdr();
// Don't set message length here.
msgHeader.messageId = 100;
initMessage theInitrequest = new initMessage();
theInitrequest.messageHeader = msgHeader;
theInitrequest.version = 200;
//
// Hopefully here
// Initrequest.messageHeader.messageLength = 3
// Initrequest.messageHeader.messageId = 100
// Initrequest.version = 200;
Console.WriteLine(theInitrequest.messageHeader.mes sageLength.ToString());
Console.WriteLine(theInitrequest.messageHeader.mes sageId.ToString());
Console.WriteLine(theInitrequest.version.ToString( ));
// and
// Initrequest.Data [0] = 3
// Initrequest.Data [1] = 100;
// Initrequest.Data [2] = 200;
Console.WriteLine(theInitrequest.Data[0].ToString());
Console.WriteLine(theInitrequest.Data[1].ToString());
Console.WriteLine(theInitrequest.Data[2].ToString());
}
}
public class Utility
{
public static void Pack(byte src, ref byte[] Data, ref uint
Index)
{
Data[Index++] = src;
}
public static void Unpack(ref byte dst, byte[] Data, ref uint
Index)
{
dst = Data[Index++];
}
}
public class initMessage
{
public msgHdr messageHeader;
public byte version;
private byte[] _internalBuffer;
public byte[] Data
{
set
{
uint index = 0;
Array.Copy(_internalBuffer, index, messageHeader.Data,
0, messageHeader.Data.Length);
index = index +
System.Convert.ToByte(messageHeader.Data.Length);
Utility.Unpack(ref version, value, ref index);
}
get
{
uint index = 0;
_internalBuffer = new byte[20];
Array.Copy(messageHeader.Data, 0, _internalBuffer,
index, messageHeader.Data.Length);
index = index +
System.Convert.ToByte(messageHeader.Data.Length);
Utility.Pack(version, ref _internalBuffer, ref index);
messageHeader.messageLength =
System.Convert.ToByte(index);
return _internalBuffer;
}
}
}
public class msgHdr
{
public byte messageLength;
public byte messageId;
private byte[] _internalBuffer = new byte[2];
public byte[] Data
{
set
{
uint index = 0;
Utility.Unpack(ref messageLength, value, ref index);
Utility.Unpack(ref messageId, value, ref index);
}
get
{
uint index = 0;
Utility.Pack(messageLength, ref _internalBuffer, ref
index);
Utility.Pack(messageId, ref _internalBuffer, ref
index);
return _internalBuffer;
}
}
}
}