Golang: how can I call win32 API without cgo?

2019-04-27 13:52发布

问题:

I'm trying to call GetUserNameEx from secur32.dll like this:

dll, err := syscall.LoadDLL("secur32.dll")
if err != nil {
    log.Fatal(err)
}
defer dll.Release()

GetUserNameEx, err := dll.FindProc("GetUserNameExW")
if err != nil {
    log.Fatal(err)
}
arr := make([]uint8, 256)
var size uint
GetUserNameEx.Call(3, uintptr(unsafe.Pointer(&arr[0])), uintptr(unsafe.Pointer(&size)))
fmt.Println(arr)
fmt.Println(size)

This code compiles fine, but GetUserNameEx.Call() will fail. I don't know why I cannot get UserName. Could anyone help me?

回答1:

size is an in-out parameter. When you make the call, you have to set it to the size of the buffer (arr). Also its type is PULONG, so in Go use uint32. Windows PULONG type is a pointer to a ULONG (which has range 0..4294967295). See source.

Also Call() returns 3 values:

func (p *Proc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error)

Store the returned lastErr and print it. Would you have done so, you would find the error earlier:

_, _, lastErr := GetUserNameEx.Call(
    3, uintptr(unsafe.Pointer(&arr[0])), uintptr(unsafe.Pointer(&size)))

fmt.Println(lastErr)

Prints:

More data is available.

This means more data is available than what fits into the buffer you pass - or rather - by the size you indicated with the in-out parameter size (you passed 0 as the size).

Working code (note the division by 2 due to unicode and minus 1 for the terminating '\0' byte / character for the size calculation):

arr := make([]uint8, 256)
var size uint32 = uint32(len(arr)) / 2 - 1
_, _, lastErr := GetUserNameEx.Call(
    3, uintptr(unsafe.Pointer(&arr[0])), uintptr(unsafe.Pointer(&size)))

fmt.Println(lastErr)
fmt.Println(string(arr))
fmt.Println(arr)
fmt.Println(size)

In this case lastErr will be:

The operation completed successfully.

To properly handle error:

The returned error is always non-nil, constructed from the result of GetLastError. Callers must inspect the primary return value to decide whether an error occurred (according to the semantics of the specific function being called) before consulting the error. The error will be guaranteed to contain syscall.Errno.

Example:

r1, _, lastErr := GetUserNameEx.Call(
    3, uintptr(unsafe.Pointer(&arr[0])), uintptr(unsafe.Pointer(&size)))

if r1 == 0 {
    fmt.Println("ERROR:", lastErr.Error())
    return
}
// No error, proceed to print/use arr