1

我正在尝试使用该memcmp方法比较 2 个小图像块。我看到了这个答案我可以比较两个相同大小的位图以确定它们是否相同的最快方法是什么? 我试图在我的项目中实现这一点:

private void Form1_Load(object sender, EventArgs e)
{
    Bitmap prev, curr;

    prev = (Bitmap) Image.FromFile(@"C:\Users\Public\Desktop\b.png");



    curr = (Bitmap)Image.FromFile(@"C:\Users\Public\Desktop\b.png");
    MessageBox.Show(CompareMemCmp(prev, curr).ToString());
}

这是方法-

[DllImport("msvcrt.dll")]
private static extern int memcmp(IntPtr b1, IntPtr b2, long count);

public static bool CompareMemCmp(Bitmap b1, Bitmap b2)
{
    if ((b1 == null) != (b2 == null)) return false;
    if (b1.Size != b2.Size) return false;

    var bd1 = b1.LockBits(new Rectangle(new Point(0, 0), b1.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
    var bd2 = b2.LockBits(new Rectangle(new Point(0, 0), b2.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

    try
    {
        IntPtr bd1scan0 = bd1.Scan0;
        IntPtr bd2scan0 = bd2.Scan0;

        int stride = bd1.Stride;
        int len = stride * b1.Height;

        return memcmp(bd1scan0, bd2scan0, len) == 0;
    }
    finally
    {
        b1.UnlockBits(bd1);
        b2.UnlockBits(bd2);
    }
}

memcmp我在调用函数时收到此错误

A call to PInvoke function 'WindowsFormsApplication1!WindowsFormsApplication1.Form1::memcmp' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

知道为什么会这样吗?我都是根据那个答案做的。

4

1 回答 1

2

正确的签名是:

[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int memcmp(IntPtr b1, IntPtr b2, IntPtr count);

因为在 C 中,countsize_t,所以它可以是 32 位或 64 位,具体取决于程序是以 32 位还是 64 位运行。

然后使用它:

return memcmp(bd1scan0, bd2scan0, (IntPtr)len) == 0;
于 2015-07-23T13:37:01.207 回答