-1
PInkove部分取自一些SO回答(對不起,我失去了原來的鏈接)。來自PInvoke的memcmp在C#中對於大於4x4的數組無法正常工作
以下是完整的程序。輸出是false
。
using System;
using System.Runtime.InteropServices;
namespace Memcpy
{
class Program
{
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int memcmp(Array b1, Array b2, long count);
public static bool CompareArrays(Array b1, Array b2)
{
// Validate buffers are the same length.
// This also ensures that the count does not exceed the length of either buffer.
return b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0;
}
static void Main(string[] args)
{
var array1 = new int[,]
{
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
var array2 = new int[,]
{
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
Console.WriteLine(CompareArrays(array1, array2));
}
}
}
如果我改變陣列的大小在4x4輸出變爲true
爲什麼memcmp這樣的行爲?
你認爲b1.Length的價值是什麼? – pm100
'CompareArrays'裏面的長度都是相等的,memcmp的結果不是= 0。 只需設置一個斷點: 'b1.Length = 20' 'b2.Length = 20' –
'memcmp'需要兩個空指針和以字節爲單位的長度。是什麼讓你認爲數組的'Length'屬性是以字節爲單位的長度?不是,它是數組中元素的數量。另外,你可能想調用'memcmp',因爲你認爲這是一個有效的函數?它是,但生成的編組代碼可能不是!事實上,我認爲編組代碼可能是這裏的罪魁禍首。 –