我正在尝试创建一个属性,它将从我的字节数组(byte [])生成一个指针(byte*),这确实有效,但每当我修改这个返回的指针时,我的字节数组都不会被修改,这是一块我想要使用的代码.
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
此外,我意识到我可以简单地删除属性并将代码放在函数中,这可能会起作用,但是我试图找出使用该属性的方法 - 除非这会降低性能,在这种情况下请让我知道.
在这里使用指针(在C#中)毫无意义.
请注意,如果使用替换Pointer属性
public byte[] Data { get { return _packet; } }
Run Code Online (Sandbox Code Playgroud)
你有一个属性,它返回对字节数组的引用,它允许你在数组中作为指针进行相同的编辑,而不需要在任何时候复制数组.
在Write16中,另一条建议使用:
byte[] data = BitConverter.GetBytes(value);
data.CopyTo(_packet, _positiion);
_position += data.Length;
Run Code Online (Sandbox Code Playgroud)