github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/utils/memory/memory_windows.go (about)

     1  //go:build windows
     2  // +build windows
     3  
     4  package memory
     5  
     6  import (
     7  	"syscall"
     8  	"unsafe"
     9  )
    10  
    11  // omitting a few fields for brevity...
    12  // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx
    13  type memStatusEx struct {
    14  	dwLength     uint32
    15  	dwMemoryLoad uint32
    16  	ullTotalPhys uint64
    17  	ullAvailPhys uint64
    18  	unused       [5]uint64
    19  }
    20  
    21  func sysTotalMemory() uint64 {
    22  	kernel32, err := syscall.LoadDLL("kernel32.dll")
    23  	if err != nil {
    24  		return 0
    25  	}
    26  	// GetPhysicallyInstalledSystemMemory is simpler, but broken on
    27  	// older versions of windows (and uses this under the hood anyway).
    28  	globalMemoryStatusEx, err := kernel32.FindProc("GlobalMemoryStatusEx")
    29  	if err != nil {
    30  		return 0
    31  	}
    32  	msx := &memStatusEx{
    33  		dwLength: 64,
    34  	}
    35  	r, _, _ := globalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msx)))
    36  	if r == 0 {
    37  		return 0
    38  	}
    39  	return msx.ullTotalPhys
    40  }
    41  
    42  func sysFreeMemory() uint64 {
    43  	kernel32, err := syscall.LoadDLL("kernel32.dll")
    44  	if err != nil {
    45  		return 0
    46  	}
    47  	// GetPhysicallyInstalledSystemMemory is simpler, but broken on
    48  	// older versions of windows (and uses this under the hood anyway).
    49  	globalMemoryStatusEx, err := kernel32.FindProc("GlobalMemoryStatusEx")
    50  	if err != nil {
    51  		return 0
    52  	}
    53  	msx := &memStatusEx{
    54  		dwLength: 64,
    55  	}
    56  	r, _, _ := globalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msx)))
    57  	if r == 0 {
    58  		return 0
    59  	}
    60  	return msx.ullAvailPhys
    61  }