bri*_*ner 3 .net c# pinvoke c++-cli memcmp
我想有效地比较部分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)
}
Run Code Online (Sandbox Code Playgroud)
我应该使用C++/CLI来做到这一点吗?
我应该在IntPtr中使用PInvoke吗?怎么样?
谢谢.
小智 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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可能还想添加一些参数验证.
C++/CLI肯定是最干净的,但是如果你还没有使用C++/CLI,这几乎没有理由将C++/CLI添加到你的项目中.
如何Marshal.UnsafeAddrOfPinnedArrayElement(数组,偏移量)?