4

我想有效地比较部分byte[]- 所以我理解memcmp()应该使用。

我知道我可以使用 PInvoke 来调用memcmp()-在 .NET 中比较两个字节数组

但是,我只想比较部分byte[]- 使用偏移量,并且没有memcmp()使用偏移量,因为它使用指针。

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

我应该使用 C++/CLI 来做到这一点吗?

我应该将 PInvoke 与 IntPtr 一起使用吗?如何?

谢谢你。

4

5 回答 5

14
[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);
    }
}

您可能还想添加一些参数验证。

于 2010-09-15T13:42:07.330 回答
5

C++/CLI 肯定是最干净的,但是如果您还没有使用 C++/CLI,这很难证明将 C++/CLI 添加到您的项目中是合理的。

Marshal.UnsafeAddrOfPinnedArrayElement(数组,偏移量)怎么样?

于 2010-06-09T02:48:01.787 回答
3

无论您做什么,都应该检查偏移量/计数值对于给定的字节数组是否有效。在你这样做之后,我看不出for在 C# 中执行循环会比 P/Invoking Win32 方法慢。似乎在 P/Invoke 中会有很多开销,这是不值得的。

此外,总是存在不安全的 C#。

与所有性能问题一样,您应该进行自己的性能测试。但在我看来,您正试图过早地优化性能。

于 2010-06-08T20:36:25.590 回答
2

无需在 C++/CLI 中进行 P/Invoke。使用 pin_ptr<> 固定阵列。这会给你一个字节*,只需添加偏移量。

于 2010-06-08T20:32:57.497 回答
0

还有一种方法

来自 System.Linq 的 SequenceEqual

 byte[] ByteArray1 = null;
 byte[] ByteArray2 = null;

 ByteArray1 = MyFunct1();
 ByteArray2 = MyFunct2();

 if (ByteArray1.SequenceEqual<byte>(ByteArray2))
 {
    MessageBox.Show("Same");
 }
 else
 {
   MessageBox.Show("Not Equal");
 }
于 2017-07-18T12:15:12.983 回答