osext_windows.go 805 B

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //+build !go1.8
  5. package osext
  6. import (
  7. "syscall"
  8. "unicode/utf16"
  9. "unsafe"
  10. )
  11. var (
  12. kernel = syscall.MustLoadDLL("kernel32.dll")
  13. getModuleFileNameProc = kernel.MustFindProc("GetModuleFileNameW")
  14. )
  15. // GetModuleFileName() with hModule = NULL
  16. func executable() (exePath string, err error) {
  17. return getModuleFileName()
  18. }
  19. func getModuleFileName() (string, error) {
  20. var n uint32
  21. b := make([]uint16, syscall.MAX_PATH)
  22. size := uint32(len(b))
  23. r0, _, e1 := getModuleFileNameProc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size))
  24. n = uint32(r0)
  25. if n == 0 {
  26. return "", e1
  27. }
  28. return string(utf16.Decode(b[0:n])), nil
  29. }