V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
hucs2542
V2EX  ›  Go 编程语言

求教大神,如果想学会怎么使用 unsafe 这个包...该怎么学...

  •  
  •   hucs2542 · 2019-08-20 20:51:20 +08:00 · 2127 次点击
    这是一个创建于 1681 天前的主题,其中的信息可能已经有所发展或是发生改变。
    以下的代码说实在,看不懂...
    import (
    "unsafe"
    "reflect"
    )

    func isChanClosed(ch interface{}) bool {
    if reflect.TypeOf(ch).Kind() != reflect.Chan {
    panic("only channels!")
    }
    cptr := *(*uintptr)(unsafe.Pointer(
    unsafe.Pointer(uintptr(unsafe.Pointer(&ch)) + unsafe.Sizeof(uint(0))),
    ))

    // this function will return true if chan.closed > 0
    // see hchan on https://github.com/golang/go/blob/master/src/runtime/chan.go
    // type hchan struct {
    // qcount uint // total data in the queue
    // dataqsiz uint // size of the circular queue
    // buf unsafe.Pointer // points to an array of dataqsiz elements
    // elemsize uint16
    // closed uint32
    // **

    cptr += unsafe.Sizeof(uint(0))*2
    cptr += unsafe.Sizeof(unsafe.Pointer(uintptr(0)))
    cptr += unsafe.Sizeof(uint16(0))
    return *(*uint32)(unsafe.Pointer(cptr)) > 0
    }
    2 条回复    2019-08-24 09:07:03 +08:00
    vy0b0x
        1
    vy0b0x  
       2019-08-21 02:02:36 +08:00
    先通过反射获取空接口变量的类型 检查是否为 channel
    确认是 channel 之后获取此变量在内存中的位置 也就是制造了一个指针

    注释是 channel 的数据结构
    unsafe.Sizeof(uint(0))*2 是跳过 qcount 和 dataqsiz
    unsafe.Sizeof(unsafe.Pointer(uintptr(0))) 是跳过 buf
    unsafe.Sizeof(uint16(0))是跳过 elemsize
    *(*uint32)(unsafe.Pointer(cptr))取得结构中 closed 地址的数据 检查是否大于 0

    可以先学 c 语言 看这些就容易很多了
    reus
        2
    reus  
       2019-08-24 09:07:03 +08:00
    垃圾代码,要是 chan 的实现变了,这个代码就会无声无息地返回错误结果。
    不用学,免得写出这种半桶水的东西坑别人。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3229 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 11:40 · PVG 19:40 · LAX 04:40 · JFK 07:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.