doulu4534 2018-05-15 20:15
浏览 108
已采纳

为什么Win32 API syscall中使用的缓冲区强制转换为[1 << 20] <type>数组?

I'm writing a golang application which interacts with Windows Services using the windows/svc package.

When I'm looking at the package source code how syscalls are being done I see interesting cast construct:

name := syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(s.ServiceName))[:]

Extracted from mgr.go

This is a common patttern when dealing with Win32 API when one needs to pass a pre-allocated buffer to receive a value from Win32 API function, usually an array or a structure.

I understand that Win API returns a unicode string represented by its pointer and it is passed to the syscall.UTF16ToString(s []uint16) function to convert it to the go string in this case.

I'm confused from the part when an unsafe pointer is cast to the pointer to 1M array, *[1<<20]uint16.

Why the size if 1M [1<<20]?

Buffer for a value is allocated dynamically, not with fixed size of 1M.

  • 写回答

1条回答 默认 最新

  • dt20081409 2018-05-15 22:50
    关注

    You need to choose a static size for the array type, so 1<<20 is chosen to be large enough to allow for any reasonable buffer returned by the call.

    There is nothing special about this size, sometimes you'll see 1<<31-1 since it's the largest array for 32bit platforms, or 1<<30 since it looks nicer. It really doesn't matter as long as the type can contain the returned data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!