首页 > 解决方案 > Why does this function work well on my main machine but not on a virtual one? (GetPhysicallyInstalledSystemMemory)

问题描述

I have the following code that (correctly) gives me the total installed memory on my computer (note, not the total physical memory, which would be a little less than the installed memory):

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());
        }

However, when I run it on my test virtual machine, it gives me 1GB less than it should (don't know if the amount matters, but bottom line it's giving me a wrong value). Any possible causes for this?

标签: c#virtual-machinekernel32

解决方案


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

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


推荐阅读