doucheng9058
2019-06-12 04:12
浏览 184
已采纳

interface {}转换为unsafe.Pointer问题

I am doing some test about unsafe.Pointer. Suppose TestFun is a common library function, so "Person" struct should not appear in this function

type Person struct {
    Name string
}

func main() {
    p := &Person{}
    p.Name = "TestName"
    TestFun(p)
}

func TestFun(val interface{}) {
    // I want to convert interface{} to unsafe.Pointer
    var pointer unsafe.Pointer

    // This Line compile error
    //pointer = unsafe.Pointer(val)

    // This is ok, but "Person" appears. This function is a common function, "Person" should not appear
    // pointer = unsafe.Pointer(val.(*Person))

    println(pointer)
}

How could I do this ?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doumi0737 2019-06-12 04:48
    已采纳

    Instead of unsafe.Pointer(val), use unsafe.Pointer(&val). Because it accepts pointer.

    package main
    
    import (
        "unsafe"
    
    )
    type Person struct {
        Name string
    }
    
    func main() {
        p := &Person{}
        p.Name = "TestName"
    
        TestFun(p)
    }
    
    func TestFun(val interface{}) {
        // I want to convert interface{} to unsafe.Pointer
        var pointer unsafe.Pointer
    
        pointer = unsafe.Pointer(&val)
    
        println(pointer)
    
        u := (*interface{})(pointer)
        p := (*u).(*Person)
        println(p.Name)
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题