user2675699
user2675699

Reputation:

Query total physical memory in Windows with Golang

Trying to get the total physical memory using Go on Windows but not sure which package(s) to use and calls to make. I believe this can be done with syscall. Would also prefer not to interface with C to do this.

Upvotes: 5

Views: 3050

Answers (1)

SirDarius
SirDarius

Reputation: 42889

The official online godoc for the syscall package at https://golang.org/pkg/syscall/ seems to document Linux APIs so it is somewhat hard to find the resources online.

First thing to do is to run godoc on the Windows platform, or on any platform by changing the values of GOOS and GOARCH.

For example, the following commands run in a Linux shell allow godoc to believe it runs on Windows, and therefore document the corresponding files:

export GOOS=windows
export GOARCH=amd64
godoc -http=:8080

Accessing http://localhost:8080/pkg/syscall/ in a browser shows the Windows syscall API docs.

A quick search reveals an interesting function on MSDN, namely GetPhysicallyInstalledSystemMemory (see https://msdn.microsoft.com/en-us/library/windows/desktop/cc300158(v=vs.85).aspx).

Apparently, this function does not exist in the Windows Go syscall package, so calling it directly is not possible.

Since the MSDN page shows that this function is present in kernel32.dll a solution given by this page (https://github.com/golang/go/wiki/WindowsDLLs) exists, that does not involve interfacing with C.
Adapting the technique to this function gives us the following code:

//+build windows
package main

import (
    "fmt"
    "syscall"
    "unsafe"
)

func main() {
    var mod = syscall.NewLazyDLL("kernel32.dll")
    var proc = mod.NewProc("GetPhysicallyInstalledSystemMemory")
    var mem uint64

    ret, _, err := proc.Call(uintptr(unsafe.Pointer(&mem)))
    fmt.Printf("Ret: %d, err: %v, Physical memory: %d\n", ret, err, mem)
}

When run, this outputs:

Ret: 1, err: L’opération a réussi., Physical memory: 16777216

The value is given in kilobytes, so divide by 1048576 (1024*1024) to obtain a value in gigabytes.

Upvotes: 5

Related Questions