How to properly output a string in a Windows console with go?

前端 未结 4 1090
难免孤独
难免孤独 2021-01-04 13:32

I have a exe in go which prints utf-8 encoded strings, with special characters in it.
Since that exe is made to be used from a console window, its output is

4条回答
  •  春和景丽
    2021-01-04 13:50

    // Alert: This is Windows-specific, uses undocumented methods, does not
    // handle stdout redirection, does not check for errors, etc.
    // Use at your own risk.
    // Tested with Go 1.0.2-windows-amd64.
    
    package main
    
    import "unicode/utf16"
    import "syscall"
    import "unsafe"
    
    var modkernel32 = syscall.NewLazyDLL("kernel32.dll")
    var procWriteConsoleW = modkernel32.NewProc("WriteConsoleW")
    
    func consolePrintString(strUtf8 string) {
        var strUtf16 []uint16
        var charsWritten *uint32
    
        strUtf16 = utf16.Encode([]rune(strUtf8))
        if len(strUtf16) < 1 {
            return
        }
    
        syscall.Syscall6(procWriteConsoleW.Addr(), 5,
            uintptr(syscall.Stdout),
            uintptr(unsafe.Pointer(&strUtf16[0])),
            uintptr(len(strUtf16)),
            uintptr(unsafe.Pointer(charsWritten)),
            uintptr(0),
            0)
    }
    
    func main() {
        consolePrintString("Hello ☺\n")
        consolePrintString("éèïöîôùòèìë\n")
    }
    

提交回复
热议问题