0

An example will make this clear:

unsafe void ProcessUnmanagedBuffer( float * buffer, int length )
{
    int i;
    for( i = 0; i < length; i++ )
    {
        buffer[ i ] = ...;
    }
}

void ProcessManagedBuffer( float[] buffer, int length )
{
    int i;
    for( i = 0; i < length; i++ )
    {
        buffer[ i ] = ...;
    }
}

// common interface to avoid duplicate code?
void ProcessBuffer( IndexableThing buffer, int length )

Of course, there can't be a common interface since float * isn't a class.

The obvious solution is to wrap and override the indexer, but for performance critical code this is far from ideal.

The less obvious one would be to pin the float[] and get a pointer to it. Better, but pinning incurs some overhead too.

I suspect there is no good solution - any ideas?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Gregzo
  • 1,194
  • 7
  • 18
  • 1
    This may be helpful http://www.codeproject.com/Articles/32125/Unmanaged-Arrays-in-C-No-Problem or here https://msdn.microsoft.com/en-us/library/z6cfh6e6%28v=vs.110%29.aspx – scotru Feb 15 '15 at 09:10
  • Thanks. I was aware of the first article, but not of that particular documentation page. – Gregzo Feb 15 '15 at 09:21
  • I can't really tell what this question is asking. Use the *fixed* keyword in C# to generate a float* and bypass the array bounds check. Make the ProcessManagedBuffer() method fast by not using the *length* argument but *buffer.Length* instead. Which allows the jitter to see that the index can't ever be out of bounds, it eliminates the bounds check. And whatever you do, profile first. The bounds check is very cheap compared to the memory access. – Hans Passant Feb 15 '15 at 10:22
  • Thanks for the suggestions, wasn't aware that using Array.Length resulted in optimizations - good to know! – Gregzo Feb 15 '15 at 10:28
  • @Hans Passant: I'm trying to avoid duplicate code in my audio processing classes: handling managed or unmanaged buffers ideally shouldn't result in 2 separate code paths. Fixed is a good idea, but I read it incurs quite a bit of overhead. I'll benchmark... – Gregzo Feb 15 '15 at 10:31
  • Found some benchmark result: http://stackoverflow.com/questions/8497018/what-is-the-overhead-of-c-sharp-fixed-statement-on-a-managed-unsafe-struct-conta Doesn't look too good for fixed. I'll try pinning more persistently with GCHandle.Alloc. – Gregzo Feb 15 '15 at 10:38

0 Answers0