doushenken2833 2015-06-09 21:22 采纳率: 0%
浏览 344
已采纳

使用Golang在Windows中查询总物理内存

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.

  • 写回答

1条回答 默认 最新

  • dp7311 2015-06-09 22:03
    关注

    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
    ", 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?