douyingmou1389 2015-03-21 22:21
浏览 14

从不安全中获取特定字节片段的最佳(最安全+性能最佳)方法是什么

I'm trying to convert this c++ to go.

This is in short what the c code is doing:

static const char *pSharedMem = NULL;
int sessionInfoOffset;

return pSharedMem + pHeader->sessionInfoOffset;

This is my (pseudo) go code:

var pSharedMem unsafe.Pointer
sessionInfoLen C.int

byteSlice := C.GoBytes(pSharedMem, pHeader.sessionInfoLen)
return byteSlice[pHeader.sessionInfoOffset:]

I've never really written any C code and I have no idea if this a good way of retrieving a byte slice from an unsafe.Pointer. Could go anything wrong with this (copying wrong piece of memory or something) and is this performant of am I doing something really stupid?

  • 写回答

1条回答 默认 最新

  • doujiang1939 2015-03-22 19:00
    关注

    GoBytes is going to be the safest method. You still have to ensure that the array exists for the entirety of the copy operation, but once you have the bytes copied, you know it can't be changed from cgo. As long as the memory being copied isn't too large, or the copy presents a performance problem, this is the way to go.

    If you want direct access to the bytes via a slice, you can slice it as an array like so:

    size := pHeader.sessionInfoLen
    byteSlice := (*[1<<30]byte)(pSharedMem)[:size:size]
    

    This saves you the copy, but you then have to manage concurrent access from cgo, and ensure the memory isn't released while you're accessing it from Go.

    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器