我想有效地比较 byte[]
的部分 - 所以我知道应该使用 memcmp()
。
我知道我可以使用 PInvoke 调用 memcmp()
- Comparing two byte arrays in .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 一起使用吗?怎么办?
谢谢。
最佳答案
[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);
}
}
您可能还想添加一些参数验证。
关于c# - 如何在字节 [] 的两个部分(带偏移量)上调用 memcmp()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3000803/