Skip to content

Instantly share code, notes, and snippets.

@nathan-osman
Last active October 26, 2015 17:46
Show Gist options
  • Select an option

  • Save nathan-osman/a5e9ec3b437718e23bf3 to your computer and use it in GitHub Desktop.

Select an option

Save nathan-osman/a5e9ec3b437718e23bf3 to your computer and use it in GitHub Desktop.
Retrieve path to executable in Go on Windows
// +build windows
package main
import (
"fmt"
"syscall"
"unicode/utf16"
"unsafe"
)
func exePath() (string, error) {
l, err := syscall.LoadDLL("kernel32.dll")
if err != nil {
return "", err
}
defer l.Release()
p, err := l.FindProc("GetModuleFileNameW")
if err != nil {
return "", err
}
b := make([]uint16, syscall.MAX_PATH)
ret, _, err := p.Call(
0,
uintptr(unsafe.Pointer(&b[0])),
uintptr(len(b)),
)
if ret != 0 {
return string(utf16.Decode(b[:ret])), nil
} else {
return "", err
}
}
func main() {
p, err := exePath()
if err != nil {
panic(err)
}
fmt.Printf("Path: %s\n", p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment