為了透過 DllImport 調用 Win32 API 獲取底層系統資訊,首先需要定義與非受控記憶體佈局完全一致的結構體。本文提供三大核心結構體完整定義。
[StructLayout(LayoutKind.Sequential)]:成員按宣告順序循序排列,符合 C/C++ 結構體記憶體佈局LayoutKind.Auto (運行時重排) 與 LayoutKind.Explicit (需手動 FieldOffset) 用於 P/Invoke 場景[StructLayout(LayoutKind.Sequential)]
public struct CpuInfo
{
public uint dwOemId; // OEM ID
public uint dwPageSize; // 頁面大小
public uint lpMinimumApplicationAddress;
public uint lpMaximumApplicationAddress;
public uint dwActiveProcessorMask; // 作用中處理器遮罩
public uint dwNumberOfProcessors; // CPU 核心數
public uint dwProcessorType; // CPU 類型
public uint dwAllocationGranularity; // 配置粒度
public uint dwProcessorLevel; // CPU 等級
public uint dwProcessorRevision; // CPU 修訂版本
}
[StructLayout(LayoutKind.Sequential)]
public struct MemoryInfo
{
public uint dwLength; // 結構大小
public uint dwMemoryLoad; // 記憶體使用率 (%)
public uint dwTotalPhys; // 總物理記憶體
public uint dwAvailPhys; // 可用物理記憶體
public uint dwTotalPageFile; // 總分頁檔案
public uint dwAvailPageFile; // 可用分頁檔案
public uint dwTotalVirtual; // 總虛擬記憶體
public uint dwAvailVirtual; // 可用虛擬記憶體
}
[StructLayout(LayoutKind.Sequential)]
public struct SystemTimeInfo
{
public ushort wYear; // 年
public ushort wMonth; // 月
public ushort wDayOfWeek; // 星期
public ushort wDay; // 日
public ushort wHour; // 時
public ushort wMinute; // 分
public ushort wSecond; // 秒
public ushort wMilliseconds;// 毫秒
}
這些結構體將在下篇配合 kernel32.dll 的 GetSystemInfo、GlobalMemoryStatus、GetSystemTime 實現完整資訊讀取功能。