Created
June 8, 2016 19:04
-
-
Save jaredwarren/508f7fdc24bfa26195307eac6bf13151 to your computer and use it in GitHub Desktop.
Go Create GUID
This file contains 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
package main | |
import ( | |
"fmt" | |
"strings" | |
"syscall" | |
"unsafe" | |
) | |
var _ unsafe.Pointer | |
var ( | |
modwinspool = syscall.NewLazyDLL("Ole32.dll") | |
CoCreateGuid = modwinspool.NewProc("CoCreateGuid") | |
StringFromGUID2 = modwinspool.NewProc("StringFromGUID2") | |
) | |
type GUID struct { | |
Data1 uint32 | |
Data2 uint16 | |
Data3 uint16 | |
Data4 [8]byte | |
} | |
func main() { | |
guid := &GUID{} | |
err := GetGuid(guid) | |
if err != nil { | |
fmt.Println(err) | |
} | |
guidString, err := GuidToString(guid) | |
if err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println(guidString) | |
} | |
func GetGuid(pguid *GUID) (err error) { | |
r1, _, e1 := syscall.Syscall(CoCreateGuid.Addr(), 1, uintptr(unsafe.Pointer(pguid)), 0, 0) | |
if r1 != 0 { | |
if e1 != 0 { | |
err = error(e1) | |
} else { | |
err = syscall.EINVAL | |
} | |
} | |
return | |
} | |
func GuidToString(pguid *GUID) (guidStr string, err error) { | |
b := make([]uint16, 39) | |
n := uint32(len(b)) | |
r1, _, e1 := syscall.Syscall(StringFromGUID2.Addr(), 3, uintptr(unsafe.Pointer(pguid)), uintptr(unsafe.Pointer(&b[0])), uintptr(n)) | |
if r1 != 0 { | |
if e1 != 0 { | |
err = error(e1) | |
} else { | |
err = syscall.EINVAL | |
} | |
} | |
guidStr = syscall.UTF16ToString(b) | |
guidStr = strings.TrimRight(guidStr, "}") | |
guidStr = strings.TrimLeft(guidStr, "{") | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment