go 调用windows dll 的方法
程序员文章站
2022-05-21 17:42:06
go 调用windows dll 的方法 ,代码如下: ......
go 调用windows dll 的方法 ,代码如下:
package main
import (
"fmt"
"syscall"
"time"
"unsafe"
)
const (
mb_ok = 0x00000000
mb_okcancel = 0x00000001
mb_abortretryignore = 0x00000002
mb_yesnocancel = 0x00000003
mb_yesno = 0x00000004
mb_retrycancel = 0x00000005
mb_canceltrycontinue = 0x00000006
mb_iconhand = 0x00000010
mb_iconquestion = 0x00000020
mb_iconexclamation = 0x00000030
mb_iconasterisk = 0x00000040
mb_usericon = 0x00000080
mb_iconwarning = mb_iconexclamation
mb_iconerror = mb_iconhand
mb_iconinformation = mb_iconasterisk
mb_iconstop = mb_iconhand
mb_defbutton1 = 0x00000000
mb_defbutton2 = 0x00000100
mb_defbutton3 = 0x00000200
mb_defbutton4 = 0x00000300
)
func abort(funcname string, err syscall.errno) {
panic(funcname + " failed: " + err.error())
}
var (
// kernel32, _ = syscall.loadlibrary("kernel32.dll")
// getmodulehandle, _ = syscall.getprocaddress(kernel32, "getmodulehandlew")
user32, _ = syscall.loadlibrary("user32.dll")
messagebox, _ = syscall.getprocaddress(user32, "messageboxw")
)
func intptr(n int) uintptr {
return uintptr(n)
}
func strptr(s string) uintptr {
return uintptr(unsafe.pointer(syscall.stringtoutf16ptr(s)))
}
func messagebox(caption, text string, style uintptr) (result int) {
ret, _, callerr := syscall.syscall9(messagebox,
4,
0,
strptr(text),
strptr(caption),
style,
0, 0, 0, 0, 0)
if callerr != 0 {
abort("call messagebox", callerr)
}
result = int(ret)
return
}
//func getmodulehandle() (handle uintptr) {
// if ret, _, callerr := syscall.syscall(getmodulehandle, 0, 0, 0, 0); callerr != 0 {
// abort("call getmodulehandle", callerr)
// } else {
// handle = ret
// }
// return
//}
// windows下的另一种dll方法调用
func showmessage2(title, text string) {
user32 := syscall.newlazydll("user32.dll")
messageboxw := user32.newproc("messageboxw")
messageboxw.call(intptr(0), strptr(text), strptr(title), intptr(0))
}
// windows下的第三种dll方法调用
func showmessage3(title, text string) {
user32,_ := syscall.loaddll("user32.dll")
messageboxw,_ := user32.findproc("messageboxw")
messageboxw.call(intptr(0), strptr(text), strptr(title), intptr(0))
}
func main() {
// defer syscall.freelibrary(kernel32)
defer syscall.freelibrary(user32) //释放指定的动态链接库
showmessage2("windows下的另一种dll方法调用", "hello !")
showmessage3("windows下的第三种dll方法调用", "hello3 !")
//fmt.printf("retern: %d\n", messagebox("done title", "this test is done.", mb_yesnocancel))
num := messagebox("done title", "this test is done.", mb_yesnocancel)
fmt.printf("get retrun value before messagebox invoked: %d\n", num)
time.sleep(3 * time.second)
}
func init() {
fmt.print("starting up\n")
}
上一篇: 数组的选择排序