How can I get a Span from a List while avoiding needless copies?

后端 未结 3 1556
天涯浪人
天涯浪人 2021-02-04 01:29

I have a List containing some data. I would like to pass it to a function which accepts ReadOnlySpan.

List i         


        
3条回答
  •  盖世英雄少女心
    2021-02-04 02:03

    You can write your own CustomList that exposes the underlying array. It is then on user code to use this class correctly.

    In particular the CustomList will not be aware of any Span that you can obtain from the underlying backing array. After taking a Span you should not make the list do anything to create a new array or create undefined data in the old array.

    The C++ standard library allows user code to obtain direct pointers into vector backing storage. They document the conditions under which this is safe. Resizing makes it unsafe for example.

    .NET itself does something like this with MemoryStream. This class allows you access to the underlying buffer and indeed unsafe operations are possible.

提交回复
热议问题