views:

197

answers:

5

Hi,

I want to compare parts of byte[] efficiently - so I understand memcmp() should be used.

I know I can using PInvoke to call memcmp() - http://stackoverflow.com/questions/43289/comparing-two-byte-arrays-in-net

But, I want to compare only parts of the byte[] - using offset, and there is no memcmp() with offset since it uses pointers.

int CompareBuffers(byte[] buffer1, int offset1, byte[] buffer2, int offset2, int count)
{
  // Somehow call memcmp(&buffer1+offset1, &buffer2+offset2, count)
}

Should I use C++/CLI to do that?

Should I use PInvoke with IntPtr? How?

Thank you.

+1  A: 

No need to P/Invoke in C++/CLI. Use pin_ptr<> to pin the array. That gets you a byte*, just add the offset.

Hans Passant
I know. So you suggest using C++/CLI to call memcpy() and not PInvoke?
brickner
Erm, what other way did you have in mind?
Hans Passant
PInvoke, like so many references I saw but without offset capabilities. Or maybe just some unsafe code?
brickner
I'll let you think about this for a while.
Hans Passant
Thanks, I'm just not sure what will work and be fastest. If they are equivalent, I prefer C#, but I'm not sure how to write it so it would work best.
brickner
+2  A: 

No matter what you do, you should check that the offset/count values are valid for the given byte arrays. After you do that, I don't see how just doing a for loop in C# is going to be any slower than P/Invoking a Win32 method. Seems like there would be a lot of overhead in the P/Invoke that it would not be worthwhile.

Also, there is always unsafe C#.

As with all performance questions, you should do your own performance testing. But it sounds to me like you are trying to optimize for performance prematurely.

Bryan
+3  A: 

C++/CLI will definitely be the cleanest, but this hardly justifies adding C++/CLI to your project if you aren't already using it.

How about Marshal.UnsafeAddrOfPinnedArrayElement(array, offset)?

Ben Voigt
+1  A: 
[DllImport("msvcrt.dll")]
private static extern unsafe int memcmp(byte* b1, byte* b2, int count);

public static unsafe int CompareBuffers(byte[] buffer1, int offset1, byte[] buffer2, int offset2, int count)
{
    fixed (byte* b1 = buffer1, b2 = buffer2)
    {
        return memcmp(b1 + offset1, b2 + offset2, count);
    }
}

You might also want to add some parameter validation.

Cory
A: 

Buffer.BlockCopy?

jgauffin
-1. How is copying related to comparing?
brickner
Ahh. sry read memcpy
jgauffin