Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call memcmp() on two parts of byte[] (with offset)?

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

I know I can using PInvoke to call memcmp() - 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.

like image 203
brickner Avatar asked Nov 28 '22 11:11

brickner


1 Answers

[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.

like image 74
Cory Avatar answered Dec 18 '22 04:12

Cory