douyuan4357 2018-07-15 07:17
浏览 33

转换切片的字节而不复制[重复]

This question already has an answer here:

How to convert a slice of bytes to []uint16 and reverse without allocation new uint16 slice. This question focused on performance and memory consumption

</div>
  • 写回答

1条回答 默认 最新

  • duancai7002 2018-07-15 07:35
    关注

    Consider that converting = copying, except for two special cases: m:=map[string]int{};m[string(bytes)) has no allocation, similarly with append.

    Using unsafe.Pointer seems the current workaround (as its name suggests, "unsafe")

    u16 := *(*uint16)(unsafe.Pointer(&byte_array[4]))
    

    There is a proposal to use unsafe.Slice instead.
    There is also the (rejected for now) proposal golang/go issue 13656

    The problem is having to write (*[C]T)(unsafe.Pointer(v))[:n:n], for some C, T, v, and n.

    A simpler way to write that entire expression would be ideal.

    var s []byte = C.AsSlice((*byte)(ptr), n)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思