I am trying to create a property that will make a pointer (byte*) from my byte array (byte[]), this does work, however whenever I modify this returned pointer, my byte array will not be modified, this is a piece of the code I want to use.
public unsafe class PacketWriter
{
private readonly byte[] _packet;
private int _position;
public byte* Pointer
{
get
{
fixed (byte* pointer = _packet)
return pointer;
}
}
public PacketWriter(int packetLength)
{
_packet = new byte[packetLength];
}
//An example function
public void WriteInt16(short value)
{
if (value > Int16.MaxValue)
throw new Exception("PacketWriter: You cannot write " + value + " to a Int16.");
*((short*)(Pointer + _position)) = (short) value;
_position += 2;
}
//I would call this function to get the array.
public byte[] GetPacket
{
get { return _packet; }
}
}
Also, I realize I could simply remove the property and put the code inside the function, that would probably work, however I am trying to figure out a way to do it using that property – unless this decreases performance, in that case please let me know.
Using pointers here (in C#) is pointless.
Note that if you replace the
Pointerproperty withYou have a property that returns a reference to the byte array and it will let you do the same editing in the array as a pointer, without copying the array at any point.
And another piece of advice, in your Write16, use: