Ale*_*lex 4 c# pinvoke exception bitmap
我正在尝试使用以下方法比较两个图像:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 CompareMemCmp() 像这样(on_click 事件):
Bitmap img1 = new Bitmap(@"C:\1\1.png");
Bitmap img2 = new Bitmap(@"C:\1\2.png");
if (CompareMemCmp(img1, img2) == true)
{ textBox1.Text = "Same"; }
else { textBox1.Text = "Different"; }
Run Code Online (Sandbox Code Playgroud)
不幸的是抛出了一个异常:
return memcmp(bd1scan0, bd2scan0, len) == 0;
Run Code Online (Sandbox Code Playgroud)
PinvokeStackimbalance "对 PInvoke 函数 'TextRecognition!TextRecognition.Form1::memcmp' 的调用使堆栈不平衡。这可能是因为托管 PInvoke 签名与非托管目标签名不匹配。检查 PInvoke 签名的调用约定和参数是否匹配目标非托管签名。”
可能是什么问题?我已经尝试了不同的方法来解决这个问题..
[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int memcmp(byte[] b1, byte[] b2, UIntPtr count);
Run Code Online (Sandbox Code Playgroud)
编辑:pinvoke.net 已将声明的原始版本标记为仅 x64,但它似乎也可以在 x32 上正常运行,只需添加一个CallingConvention=CallingConvention.Cdecl
.