您现在的位置是:网站首页> Go语言
Go指针转换
- Go语言
- 2021-03-21
- 796人已阅读
type myClass struct {
A int
B string
}
func (c *myClass) Open() bool {
return true
}
func main() {
m_MyClass := new(myClass)
m_MyClass.A = 123
m_MyClass.B = "你好"
p1 := unsafe.Pointer(m_MyClass)
fmt.Println(p1)
p2 := uintptr(p1)
fmt.Println(p2)
y := int64(p2)
fmt.Println(y)
ptr1 := uintptr(y)
ptr2 := unsafe.Pointer(ptr1)
m_MyClass1 := (*myClass)(ptr2)
fmt.Println(m_MyClass1.B)
封装
package Share
func ClassPtr2Int64String(m_Ptr interface{}) string {
p1 := unsafe.Pointer(&m_Ptr)
fmt.Println(p1)
p2 := uintptr(p1)
fmt.Println(p2)
y := int64(p2)
fmt.Println(y)
str := strconv.FormatInt(y, 10)
return str
}
func In64String2Interface(str string) interface{} {
a, _ := strconv.ParseInt(str, 10, 64)
ptr1 := uintptr(a)
ptr2 := unsafe.Pointer(ptr1)
m_MyClass1 := (*interface{})(ptr2)
return *m_MyClass1
}
调用
type myClass struct {
A int
B string
}
func (c *myClass) Open() bool {
return true
}
func main() {
fmt.Println("Hello World!")
m_MyClass := new(myClass)
m_MyClass.A = 123
m_MyClass.B = "你好"
p1 := unsafe.Pointer(m_MyClass)
fmt.Println(p1)
p2 := uintptr(p1)
fmt.Println(p2)
y := int64(p2)
fmt.Println(y)
ptr1 := uintptr(y)
ptr2 := unsafe.Pointer(ptr1)
m_MyClass1 := (*myClass)(ptr2)
fmt.Println(m_MyClass1.B)
iii := Share.ClassPtr2Int64String(m_MyClass)
m_MyClass2 := Share.In64String2Interface(iii).(*myClass)
fmt.Println(m_MyClass2.B)
}