I have an instance of ReadOnlyMemory<byte> over a byte[] that I need to convert to ArraySegment<byte>. I'm doing this as part of a major code refactor, and I'm having to adapt an existing interface for code that can't be changed at the moment. This conversion happens for every packet captured promiscuously on a very high-traffic network, so performance is important.
My current approach is using MemoryMarshal.TryGetArray<byte>(). This works, and it's fast. To be honest, it's probably fast enough that my question amounts to more of a curiosity than a problem in need of a solution. Still...
In looking at the source code for MemoryMarshal.TryGetArray<byte>(), I noticed that it calls ReadOnlyMemory<T>.GetObjectStartLength(). This is an internal method, so it's not available for direct use. But, it returns everything I'd need to create the ArraySegment<byte> instance, and there's always reflection, right?
So for due diligence and curiosity's sake, I profiled the MemoryMarshal approach against a reflection-based approach using Benchmark.NET. As expected, the MemoryMarshal approach won handily.
That'd be the end of it, except that I stumbled across this article by @JonSkeet, and it made me wonder about the performance of using a created open delegate instance against the MethodInfo for ReadOnlyMemory<T>.GetObjectStartLength().
I implemented the approach in the article, and while it compiles, I get a runtime error due to the two int out parameters (doesn't work with Func<TTarget, TInput1, TInput2, TResult>). Even if I could figure out how to work around that, I wonder if the fact that ReadOnlyMemory<byte> is a value type wouldn't cause yet another a problem since @JonSkeet purposefully limits the solution to classes ("It's feasible, but a bit of a faff").
I think I understand how the solution works, but I cannot figure out how to get it to work for an instance method on a value type that has two out parameters. And it needs to be an open delegate, one that can take a ReadOnlyMemory<byte> as input and return the resulting byte[] and the values for both int out parameters.
Can this even be done? Like I said, this is probably an academic exercise, but I'd really love to know how such a solution would stack up performance-wise.

GetObjectStartLength()function operates against private members in theReadOnlyMemory<T>instance. I can declare a delegate that matches its signature and callDelegate.CreateDelegate()against that delegate's type and theMethodInforetrieved via reflection. But how do I get it to operate against an arbitrary instance ofReadOnlyMemory<T>?ArraySegment<byte>.MemoryMarshal.TryGetArray<byte>()gives you exactly that (if it succeed). So what would your method do differently, and why would it be better?TryGetArraydo something that you think hurt performance?