加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

如何使用go在Windows控制台中正确输出字符串?

发布时间:2020-12-14 01:59:17 所属栏目:Windows 来源:网络整理
导读:我有一个exe in go打印 utf-8个编码的字符串,其中包含特殊字符. 由于该exe用于从控制台窗口使用,因此其输出被破坏,因为Windows使用ibm850编码(也称为 code page 850 ). 你如何确保go exe为控制台窗口打印正确编码的字符串,例如打印: éè????ùòèì? 而不
我有一个exe in go打印 utf-8个编码的字符串,其中包含特殊字符.
由于该exe用于从控制台窗口使用,因此其输出被破坏,因为Windows使用ibm850编码(也称为 code page 850).

你如何确保go exe为控制台窗口打印正确编码的字符串,例如打印:

éè????ùòèì?

而不是(没有任何翻译到右边charset)

├?├?├?├?├?├┤├╣├▓├?├?├?

解决方法

// 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")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读