V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
hucs2542

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

  •  
  •   hucs2542 · Aug 20, 2019 · 2693 views
    This topic created in 2443 days ago, the information mentioned may be changed or developed.
    以下的代码说实在,看不懂...
    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 replies    2019-08-24 09:07:03 +08:00
    vy0b0x
        1
    vy0b0x  
       Aug 21, 2019
    先通过反射获取空接口变量的类型 检查是否为 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  
       Aug 24, 2019
    垃圾代码,要是 chan 的实现变了,这个代码就会无声无息地返回错误结果。
    不用学,免得写出这种半桶水的东西坑别人。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   989 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 19:32 · PVG 03:32 · LAX 12:32 · JFK 15:32
    ♥ Do have faith in what you're doing.