简体   繁体   中英

Span - access to original value

I wish to obtain the original value a Span represents. Take the following code for example, how would I, in DoWork , gain access to the original byte array without creating a copy of it ?

static void Main()
{
    var data = new byte[0x100];
    DoWork(new Span<byte>(data));
}

private void DoWork(Span<byte> Data)
{
    //var data = Data.ToArray(); Unsuitable; creates a copy
    //var data = (byte[])Data; Unsuitable; doesn't work
    //MemoryMarshal. Something in here may work, but unsure
    //MemoryExtensions. Something in here may work, but unsure
}

I found 2 static classes with helper methods (shown above) that may help, but I am unsure as to what is the best way to do this without making things slower than just making a copy.

According to the Span Document :

Because it is a stack-only type, Span is unsuitable for many scenarios that require storing references to buffers on the heap. This is true, for example, of routines that make asynchrous method calls. For such scenarios, you can use the complimentary System.Memory and System.ReadOnlyMemory types.

So maybe to your need, you don't have to use a Span:

static void Main()
{
    var data = new byte[0x100];
    DoWork(data);
}
private void DoWork(byte[] data)
{
    // data array is by reference.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM