LoginSignup
7
7

More than 5 years have passed since last update.

goでWindows APIを実行する覚書

Posted at

golangでWindows APIを実行するための覚書(入り口)です。

やってみたこと

まずは、感覚を知りたかったのでWindowsのKernel32.dllからGetTickCount関数を実行してOSの起動時間をmsで取得するプログラムを描いてみました。

ソース

package main

import (
    "fmt"
    "syscall"
)

func main() {
    // golang.org/x/sys/windows(参考)
    // https://godoc.org/golang.org/x/sys/windows
    // Win32 API 一覧(参考)
    // http://www.pinvoke.net/index.aspx

    // kernel32.dllをロード
    kernel32, err := syscall.LoadDLL("Kernel32.dll")
    if err != nil {
        panic(err)
    }
    // 一番最後に読み込んだDLLをメモリからアンロード
    // https://godoc.org/golang.org/x/sys/windows#DLL.Release
    defer kernel32.Release()

    // システムが起動してから経過した時間をミリ秒(ms)で取得する関数を指定
    // http://www.pinvoke.net/default.aspx/kernel32.GetTickCount
    proc, err := kernel32.FindProc("GetTickCount")
    if err != nil {
        panic(err)
    }

    // 起動時間を取得
    r, _, _ := proc.Call()

    // 起動時間を表示(ms)
    fmt.Println(r)
}

DLLをロードして、定義されている関数を見つけて実行する感じ。

実行

PS C:\Users\Administrator\Desktop> go run .\get_os_uptime.go
6439736

参考

Windows DLL一覧参考
GoのWindows syscallドキュメント

7
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7