gpt4 book ai didi

c# - 我正在尝试获取已安装的内存总量

转载 作者:行者123 更新时间:2023-11-30 21:53:18 25 4
gpt4 key购买 nike

我正在尝试获取总安装内存。我安装了 6GB,但这返回了 5.47GB。我该怎么做才能解决这个问题?我在 x64 PC 上构建并在 x64 PC 上运行应用程序。

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;

public MEMORYSTATUSEX()
{
this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX));
}
}

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern Boolean GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);

public static String GetTotalRam
{
get
{
ulong installedMemory = 0;
NativeMethods.MEMORYSTATUSEX memStatus = new NativeMethods.MEMORYSTATUSEX();
if (NativeMethods.GlobalMemoryStatusEx(memStatus))
{
installedMemory = memStatus.ullTotalPhys;
}
return ConvertBytes(installedMemory);
}
}

最佳答案

您发布的方法为您提供了总的可用 内存,这与总的安装 内存不完全相同。

要获取安装的内存量,您可以调用 GetPhysicallyInstalledSystemMemory功能。

我认为您会发现该链接中的备注部分很有趣:

The GetPhysicallyInstalledSystemMemory function retrieves the amount of physically installed RAM from the computer's SMBIOS firmware tables. This can differ from the amount reported by the GlobalMemoryStatusEx function, which sets the ullTotalPhys member of the MEMORYSTATUSEX structure to the amount of physical memory that is available for the operating system to use. 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.

编辑:添加示例代码

根据发现的代码修改here :

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

static void Main()
{
long memKb;
GetPhysicallyInstalledSystemMemory(out memKb);
Console.WriteLine((memKb / 1024 / 1024) + " GB of RAM installed.");
}

关于c# - 我正在尝试获取已安装的内存总量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33979385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com