I have a function of this kind of shape which does 1 dimensional rootfinding:
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
}
This is a fixed shape in order to make the algorithm reusable. Consider this a fixed library function that I cannot change (or at least needs to be kept generic and reusable and not changed for the specifics of this question).
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 clearly can't shove Span<T>
s into the object since that would require boxing and unboxing.
Using a lambda expression the calling code could look something like:
void CallingMethod()
{
Span<double> k1 = stackalloc double[n];
double answer;
Solve((x, o) => Wrapper(x, k1, o), out answer, null);
}
double Wrapper(double x, ReadOnlySpan<double> k1, object o)
{
return <some function of x and k1>;
}
But this does not work because you can't form a closure over Span<T>
s with a lambda expression. They also can't be used in a generic type, any boxing and unboxing is out, can't be passed as a params keyword, can't be on instance variables, etc.
Is there any way to solve this problem?
And just to reinforce that this example is overly simplified. I might have one Span, but the problem I'm currently working on I need to pass in 4 Span's. I need to design for any number of them.