为什么这个功能在我的主机上很好用,但在虚拟机上却不行? (GetPhysicallyInstalledSystemMemory)

Why does this function work well on my main machine but not on a virtual one? (GetPhysicallyInstalledSystemMemory)

我有以下代码(正确地)给出了我计算机上安装的总内存(注意,不是总物理内存,它会比安装内存少一点):

using System.Runtime.InteropServices;

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetPhysicallyInstalledSystemMemory(out long TotalMemoryInKilobytes);

        public float getInstalledRAM()
        {
            long memKb;
            GetPhysicallyInstalledSystemMemory(out memKb);
            return float.Parse((memKb / 1024 / 1024).ToString());
        }

但是,当我 运行 在我的测试虚拟机上使用它时,它给我的容量比应有的少了 1GB(不知道这个数量是否重要,但最重要的是它给了我一个错误的值)。这有什么可能的原因吗?

Windows 通常四舍五入总可用内存。您在 VM 下看到的结果可能只是由于整数运算截断了两个除法的结果。

强制双算术除以 1024.0 至少一次,然后查看错误是否仍然存在。