Last active
October 26, 2015 17:46
-
-
Save nathan-osman/a5e9ec3b437718e23bf3 to your computer and use it in GitHub Desktop.
Retrieve path to executable in Go on Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // +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