Break OO privacy: Difference between revisions

→‎{{header|Go}}: Correct invalid unsafe.Pointer use
(→‎{{header|Go}}: Correct invalid unsafe.Pointer use)
Line 520:
// package once we know what type it is (so we can use the
// correct pointer type, here *int):
vp := v.Field(1).Addr() // Take the fields's address
uipup := unsafe.Pointer(vp.Pointer() ) // … get an int value of the address and convert it "unsafely"
p := (*int)(up) // … and end up with what we want/need
up := unsafe.Pointer(uip) // … convert it "unsafely"
p := (*int)(up) // … and end up with what we want/need
fmt.Printf(" vp has type %-14T = %v\n", vp, vp)
fmt.Printf(" uip has type %-14T = %#0x\n", uip, uip)
fmt.Printf(" up has type %-14T = %#0x\n", up, up)
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p)
Line 531 ⟶ 529:
// or an incr all on one ulgy line:
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++
 
// Note that as-per the package "unsafe" documentation,
// the return value from vp.Pointer *must* be converted to
// unsafe.Pointer in the same expression; the result is fragile.
//
// I.e. it is invalid to do:
// thisIsFragile := vp.Pointer()
// up := unsafe.Pointer(thisIsFragile)
}
 
Line 557 ⟶ 563:
1: unexported int false
vp has type reflect.Value = <*int Value>
uip has type uintptr = 0xc208000208
up has type unsafe.Pointer = 0xc208000208
p has type *int = 0xc208000208 pointing at 42
Anonymous user