Is there any way to pass
Span<T>s to a library function?
I have a library function with a fixed shape:
public delegate double Fun(double x, object o);
public static void Solve(Fun f, out double y, object o)
y = f(1.0, o); // all the irrelevant details of the algorithm omitted
I’d like to pass in a function which requires external parameters that are
Span<T>s held on the stack to avoid allocations, but
Span<T>s cannot be passed as a parameter due to boxing and unboxing, and cannot be used in a generic type, passed as a
params keyword, or stored in instance variables.
Is there any way to solve this problem?
Yes, you can use a
ref struct to pass
Span<T> to the library function. Here is an example:
public delegate double Fun(ref double x, in MySpan span);
public static void Solve(Fun f, out double y, in MySpan span)
double x = 1.0;
y = f(ref x, span);
And you can define
MySpan as a
ref struct like this:
public ref struct MySpan
public readonly int Length;
private readonly double _array;
public MySpan(double array)
_array = array;
Length = array.Length;
public ref double this[int index] => ref _array[index];
Then you can pass an instance of
Solve method and use it in your function. Note that
MySpan is a
ref struct to avoid heap allocations.