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条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog