3

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?

S. M.
  • 227
  • 1
  • 12
  • How much RAM is allocated to the VM? How much does your computer have? How much is it reporting? –  Dec 17 '18 at 16:20
  • My computer has 8,00GB, and it's reporting 8,00GB; the VM has 8,00GB and it's reporting 7,00GB. – S. M. Dec 17 '18 at 16:21
  • Does Windows inside the VM agree with 8, or 7? You can get this figure inside the VM by checking `Control Panel\All Control Panel Items\System`. –  Dec 17 '18 at 16:23
  • It agrees with 8GB – S. M. Dec 17 '18 at 16:24
  • Okay good. I wanted to rule out this might be PEBCAK. According to the [documentation](https://learn.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-getphysicallyinstalledsystemmemory), the reported value doesn't include memory reserved for drivers and such. "The amount of memory available to the operating system can be less than the amount of memory physically installed in the computer because the BIOS and some drivers may reserve memory as I/O regions for memory-mapped devices, making the memory unavailable to the operating system and applications." Might be it? –  Dec 17 '18 at 16:29
  • I believe that excerpt refers to the previously referred `GlobalMemoryStatusEx` function in that paragraph, and this one should include the memory that's usually unreachable, otherwise we'd use the `TotalPhysicalMemory` property from the `ComputerInfo` class. I could've misinterpreted though. "The amount of physical memory retrieved by the GetPhysicallyInstalledSystemMemory function must be equal to or greater than the amount reported by the GlobalMemoryStatusEx function;" meaning it should include that unavailable part of the memory. – S. M. Dec 17 '18 at 16:35
  • Hm, yeah, I think you're right. I'm not sure then, sorry. :( –  Dec 17 '18 at 16:37

1 Answers1

2

Windows normally rounds the total available memory. The result you are seeing under the VM might simply be due to integer arithmetics truncating the result of the two divisions.

Force double arithmetics dividing at least once by 1024.0 and see if the error persists.

InBetween
  • 32,319
  • 3
  • 50
  • 90