使用 Golang 查询 Windows 中的总物理内存 [英] Query total physical memory in Windows with Golang

查看:34
本文介绍了使用 Golang 查询 Windows 中的总物理内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在 Windows 上使用 Go 获取总物理内存,但不确定要使用哪些包和调用哪些包.我相信这可以通过 syscall 来完成.也不想与 C 交互来执行此操作.

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.

推荐答案

syscall 包的官方在线 godoc 位于 https://golang.org/pkg/syscall/ 似乎记录了 Linux API,因此在线查找资源有些困难.

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.

首先要做的是在Windows平台上运行godoc,或者通过改变GOOSGOARCH的值在任何平台上运行.

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

例如,在 Linux shell 中运行以下命令允许 godoc 相信它在 Windows 上运行,因此记录相应的文件:

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

在浏览器中访问 http://localhost:8080/pkg/syscall/ 会显示 Windows系统调用 API 文档.

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

快速搜索显示 MSDN 上一个有趣的功能,即 GetPhysicallyInstalledSystemMemory(请参阅 https://msdn.microsoft.com/en-us/library/windows/desktop/cc300158(v=vs.85).aspx).

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).

显然,Windows Go syscall 包中不存在此函数,因此无法直接调用它.

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

由于 MSDN 页面显示此函数存在于 kernel32.dll 中,因此该页面给出了解决方案 (https://github.com/golang/go/wiki/WindowsDLLs) 存在,不涉及与 C 的接口.
将该技术应用于此函数为我们提供了以下代码:

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)
}

运行时,输出:

返回:1,错误:L'opération a réussi.,物理内存:16777216

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

该值以千字节为单位,因此除以 1048576 (1024*1024) 即可获得以千兆字节为单位的值.

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

这篇关于使用 Golang 查询 Windows 中的总物理内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆