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

使用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.

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

报告相同问题?

悬赏问题

  • ¥60 Python如何后台操作Vmwake虚拟机键鼠
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容