golang 使用编译选项-H=windowsgui后,仍然输出log到console

时间:2019-06-11 13:30:55   收藏:0   阅读:900

大概原理:

调用syscall创建一个console,获取其handle,重定向标准输出stdout到该console。

if debug {
	modkernel32 := syscall.NewLazyDLL("kernel32.dll")
	procAllocConsole := modkernel32.NewProc("AllocConsole")
	r0, _, err0 := syscall.Syscall(procAllocConsole.Addr(), 0, 0, 0, 0)
	if r0 == 0 {
		fmt.Printf("Could not allocate console: %s. Check build flags..", err0)
		os.Exit(1)
	}
	hout, err1 := syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE)
	if err1 != nil {
		os.Exit(2)
	}
	os.Stdout = os.NewFile(uintptr(hout), "/dev/stdout")
}

  

参考链接: stackoverflow.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!