代码之家  ›  专栏  ›  技术社区  ›  brickner

如何对字节[]的两个部分(带偏移量)调用memcmp()?

  •  3
  • brickner  · 技术社区  · 14 年前

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

    我知道我可以用pinvoke打电话 MEMPP() - Comparing two byte arrays in .NET

    但是,我只想比较 字节[] -使用偏移,没有 MEMPP() 使用偏移量,因为它使用指针。

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

    我应该用C++/CLI来做吗?

    我应该在intptr中使用pinvoke吗?怎么用?

    谢谢您。

    5 回复  |  直到 7 年前
        1
  •  5
  •   Ben Voigt    14 年前

    C++/CLI肯定是最干净的,但是如果你还没有使用C++,CLI也不太有理由把它添加到你的项目中。

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

        2
  •  14
  •   Cory    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);
        }
    }
    

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

        3
  •  2
  •   Hans Passant    14 年前

    不需要在C++/CLI中调用/调用。使用pin_ptr<gt;锁定阵列。得到一个字节*,只需添加偏移量。

        4
  •  2
  •   Bryan    14 年前

    无论您做什么,都应该检查偏移/计数值对于给定的字节数组是否有效。在你这么做之后,我不知道怎么做 for C中的循环将比P/调用win32方法慢。似乎在P/Invoke中会有很多开销,这是不值得的。

    而且,总有不安全的C。

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

        5
  •  0
  •   user5377926    7 年前

    还有一条路

    序列与System.Linq相等

     byte[] ByteArray1 = null;
     byte[] ByteArray2 = null;
    
     ByteArray1 = MyFunct1();
     ByteArray2 = MyFunct2();
    
     if (ByteArray1.SequenceEqual<byte>(ByteArray2))
     {
        MessageBox.Show("Same");
     }
     else
     {
       MessageBox.Show("Not Equal");
     }