C# Copy variables into buffer without creating garbage?

后端 未结 2 1346
后悔当初
后悔当初 2021-02-08 01:01

Is it possible in C# .Net (3.5 and above) to copy a variable into a byte[] buffer without creating any garbage in the process?

For instance:

int variable         


        
2条回答
  •  清歌不尽
    2021-02-08 01:36

    Why can't you just do:

    byte[] buffer = BitConverter.GetBytes(variableToCopy);
    

    Note that the array here is not an indirection into the storage for the original Int32, it is very much a copy.

    You are perhaps worried that bytes in your example is equivalent to:

    unsafe
    {
        byte* bytes = (byte*) &variableToCopy;
    }
    

    .. but I assure you that it is not; it is a byte by byte copy of the bytes in the source Int32.

    EDIT:

    Based on your edit, I think you want something like this (requires unsafe context):

    public unsafe static void CopyBytes(int value, byte[] destination, int offset)
    {
        if (destination == null)
            throw new ArgumentNullException("destination");
    
        if (offset < 0 || (offset + sizeof(int) > destination.Length))
            throw new ArgumentOutOfRangeException("offset");
    
        fixed (byte* ptrToStart = destination)
        {
            *(int*)(ptrToStart + offset) = value;
        }
    }
    

提交回复
热议问题