github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgSys/GetCurrentExecutePath_windows.go (about)

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