Search code examples
c#heap-memoryunsafestack-memory

Passing a byte* to Stream.Read(byte[], int, int)


The .NET function Stream.Read() takes a byte[] as a parameter. Is there a way I can pass a stackalloc'd byte* instead? This would save me from having to make an extra heap allocation and in turn save time in garbage collection. This function is short and is repeatedly invoked.


Solution

  • No you can't. You need to create an array and copy it into there first. See also this thread on MSDN forums.

    Apart from that: I don't know the context of your application but maybe you can use a statically allocated buffer? In a multi threaded context you could allocate the buffer in the TLS like this:

    class SomeDataProcessor
    {
        [ThreadStatic]
        static byte[] _Buffer;
    }
    

    Note that you need to be careful with initializers though. See also here