C# Copy variables into buffer without creating garbage?

后端 未结 2 1351
后悔当初
后悔当初 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;
        }
    }
    
    0 讨论(0)
  • 2021-02-08 01:44

    Use pointers is the best and the fastest way: You can do this with any number of variables, there is no wasted memory, the fixed statement has a little overhead but it's too small

            int v1 = 123;
            float v2 = 253F;
            byte[] buffer = new byte[1024];
            fixed (byte* pbuffer = buffer)
            {
                //v1 is stored on the first 4 bytes of the buffer:
                byte* scan = pbuffer;
                *(int*)(scan) = v1;
                scan += 4; //4 bytes per int
    
                //v2 is stored on the second 4 bytes of the buffer:
                *(float*)(scan) = v2;
                scan += 4; //4 bytes per float
            }
    
    0 讨论(0)
提交回复
热议问题