Skip to content

With Span<T>.DangerousCreate gone, there are no APIs to create a Span<T> from a T[,] array (on .NET Standard 2.0) #27690

@Sergio0694

Description

@Sergio0694

Hello, I'm working on a .NET Standard 2.0 library (this one) and up until now I've used the old Span<T> APIs from the System.Memory assembly version 4.0.1.0 (from what I can see by Ctrl+click on Span<T>), and everything worked great.

I went back to update the library with the latest NuGet packages, and noticed that (according to #24562) the Span<T>.DangerousCreate(object, ref T, int) API has been removed. I tried to look for it under MemoryMarshal, but it isn't there at least on .NET Standard 2.0.

As a result, simple methods like these ones are not working anymore:

public static Span<T> AsSpan<T>([NotNull] this T[,] m) where T : struct
    => Span<T>.DangerousCreate(m, ref m[0, 0], m.Length);

public static Span<T> Slice<T>([NotNull] this T[,] m, int row) where T : struct
    => Span<T>.DangerousCreate(m, ref m[row, 0], m.GetLength(1));

Note: I'm using T : struct as I wrote this library targeting C# 7.2. I'll replace struct with unmanaged when I move the lib to C# 7.3, I know that using struct isn't a perfect constraint here.

Same for similar methods to extract a chunk of contiguous rows from a T[,] array.

I'm using 2D arrays all over this library, and all the current Span<T> APIs I see only work with classic 1D arrays. I can't use the constructor that takes a void* as if I used something like new Span<T>(Unsafe.AsPointer(ref array[0, 0])) the GC would wouldn't be able to track the ref once it gets forwarded as a pointer only.

I understand that the original DangerousCreate(object, ref T, int) had to me moved/removed and that some users were not using that API correctly, but is there some other way to still do what that API did now that it's gone? I mean, I can't see a way to properly work with 2D arrays and spans now that the API in question is no longer available.

Thanks! 😄

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions