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.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀