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.

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

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测