duanli12176 2016-12-21 16:03
浏览 421
已采纳

在没有CGO的情况下将C字符串转换为Go字符串

I'm using the Go Windows syscall libraries to get data out of a function in a DLL. This all works great, but I can't figure out a way to convert a LPCTSTR (pointer to C String) into a proper Go string without using CGO.

I'd like to avoid CGO if at all possible, because the two options for CGO code on Windows (cross-compiling, and installing gcc on windows) are still fairly complex.

  • 写回答

2条回答 默认 最新

  • dongshilve4392 2016-12-21 22:02
    关注

    If you have an 8 bit string, you can convert the LPCTSTR pointer to a []byte of the proper size, and copy it to a new string or slice.

    a := (*[1 << 30-1]byte)(unsafe.Pointer(lpctstr))
    size := bytes.IndexByte(a[:], 0)
    // if you just want a string
    // goString := string(a[:size:size])
    
    // if you want a slice pointing to the original memory location without a copy
    // goBytes := a[:size:size]
    
    goBytes := make([]byte, size)
    copy(goBytes, a)
    

    If the LPCTSTR points to an LPCWSTR which contains 16bit unicode characters, you can convert that with the utf16 package.

    a := (*[1 << 30-1]uint16)(unsafe.Pointer(lpctstr))
    size := 0
    for ; size < len(a); size++ {
        if a[size] == uint16(0) {
            break
        }
    }   
    runes := utf16.Decode(a[:size:size])
    goString := string(runes)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作