Sunday, April 15, 2012

Golang -- using shared libraries



import (
    "syscall"
    "unsafe"
)

Method I
...
mod = syscall.NewLazyDLL("file.dll")
procMyMessageBoxW = mod.NewProc("MyMessageBoxW")
message := "hello"
ret, _, _ : = procMyMessageBoxW.Call( uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(message))) );
...

//example
func main() {
var mod = syscall.NewLazyDLL("user32.dll")
var proc = mod.NewProc("MessageBoxW");
proc.Call(0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("adrian"))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("annie"))),
0);
}

Method II
...

func main() {
mod, _ := syscall.LoadLibrary("user32.dll")
defer func() {
syscall.FreeLibrary(mod)
}()
proc, _ := syscall.GetProcAddress(syscall.Handle(mod), "MessageBoxW");
syscall.Syscall6(proc, 4,
0,
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("adrian"))),
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("annie"))),
0, 0, 0);
}