doubang4881 2015-05-09 20:25
浏览 82
已采纳

Winapi GetSystemTimes函数未填充lpIdleTime / lpKernelTime / lpUserTime

I`m stuck with GetSystemTimes function. There is no any problem in c++ code, but with golang I'm getting three nils instead of expected values

My code:

package main

import (
    "log"
    "syscall"
    "unsafe"
)

var (
    modKernel32 = syscall.NewLazyDLL("kernel32.dll")
    procGetSystemTimes = modKernel32.NewProc("GetSystemTimes")
)

type SystemTimes struct {
    IdleTime   *syscall.Filetime
    KernelTime *syscall.Filetime
    UserTime   *syscall.Filetime
}

func main() {
    times, err := getSystemTimes()
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("idle=%v, kernel=%v, user=%v", times.IdleTime, times.KernelTime, times.UserTime)
}

func getSystemTimes() (times SystemTimes, err error) {
    res, _, err1 := procGetSystemTimes.Call(uintptr(unsafe.Pointer(times.IdleTime)), uintptr(unsafe.Pointer(times.KernelTime)), uintptr(unsafe.Pointer(times.UserTime)))
    if res != 1 {
        return times, err1
    }
    return
}

It's super simple and very similar to syscall`s GetProcessTimes function from stdlib. And look, what my program prints:

idle=<nil>, kernel=<nil>, user=<nil>

Why? I expect error or result, why my fields are empty?

Confguration: win8 x64, go1.4.2 windows/amd64

  • 写回答

1条回答 默认 最新

  • doupingpeng7567 2015-05-09 20:32
    关注

    You're passing the address of nil fields to the function.

    Either make it point directly to the Filetime struct or initialize all 3 fields before passing them:

    type SystemTimes struct {
        IdleTime   syscall.Filetime
        KernelTime syscall.Filetime
        UserTime   syscall.Filetime
    }
    .....
    res, _, err1 := procGetSystemTimes.Call(uintptr(unsafe.Pointer(&times.IdleTime)), uintptr(unsafe.Pointer(&times.KernelTime)), uintptr(unsafe.Pointer(&times.UserTime)))
    

    Output:

    ┌─ oneofone@Oa [/tmp]                                                                                                             
    └──➜ env CC=i686-w64-mingw32-gcc CGO_ENABLED=1 GOOS=windows GOARCH=386 go build -a /tmp/syscall.go; and wine syscall.exe
    2015/05/09 22:31:53 idle={1292275456 39}, kernel={1436840864 41}, user={3496565408 2}
    

    <kbd>playground</kbd>

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

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器