C#位图比较(PinvokeStackl失衡异常)
本文关键字:异常 PinvokeStackl 位图 比较 | 更新日期: 2023-09-27 18:25:01
我正在尝试使用比较两个图像
[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);
}
}
我使用的CompareMemCmp()是这样的(点击事件):
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"; }
不幸的是,抛出了一个异常:
return memcmp(bd1scan0, bd2scan0, len) == 0;
PinvokeStack失衡"对PInvoke函数'TextRecognition!TextRecognition.Form1::memcmp'的调用使堆栈不平衡。这可能是因为托管的PInvokes签名与非托管的目标签名不匹配。请检查PInvokee签名的调用约定和参数是否与目标非托管签名匹配。"
可能是什么问题我已经尝试了不同的方法来解决这个问题。。
pinvoke.net说签名应该是
[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int memcmp(byte[] b1, byte[] b2, UIntPtr count);
编辑:pinvoke.net已经将声明的原始版本标记为x64,但它似乎也在x32上运行良好,只添加了CallingConvention=CallingConvention.Cdecl
。
签名应该是:
[DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)]
static extern int memcmp(IntPtr b1, IntPtr b2, UIntPtr count);
问题中的代码问题是
- 调用约定之间的不匹配:
msvcrt.dll
将其函数导出为cdecl
- 计数参数是本机代码中的
size_t
,相当于.net中指针大小的无符号整数,即UIntPtr