osext_windows.go 788 B

12345678910111213141516171819202122232425262728293031323334
  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. package osext
  5. import (
  6. "syscall"
  7. "unicode/utf16"
  8. "unsafe"
  9. )
  10. var (
  11. kernel = syscall.MustLoadDLL("kernel32.dll")
  12. getModuleFileNameProc = kernel.MustFindProc("GetModuleFileNameW")
  13. )
  14. // GetModuleFileName() with hModule = NULL
  15. func executable() (exePath string, err error) {
  16. return getModuleFileName()
  17. }
  18. func getModuleFileName() (string, error) {
  19. var n uint32
  20. b := make([]uint16, syscall.MAX_PATH)
  21. size := uint32(len(b))
  22. r0, _, e1 := getModuleFileNameProc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(size))
  23. n = uint32(r0)
  24. if n == 0 {
  25. return "", e1
  26. }
  27. return string(utf16.Decode(b[0:n])), nil
  28. }