Break OO privacy: Difference between revisions
Content added Content deleted
(→{{header|Go}}: Correct invalid unsafe.Pointer use) |
|||
Line 520: | Line 520: | ||
// package once we know what type it is (so we can use the |
// package once we know what type it is (so we can use the |
||
// correct pointer type, here *int): |
// correct pointer type, here *int): |
||
vp := v.Field(1).Addr() // Take the fields's address |
vp := v.Field(1).Addr() // Take the fields's address |
||
up := unsafe.Pointer(vp.Pointer()) // … get an int value of the address and convert it "unsafely" |
|||
⚫ | |||
up := unsafe.Pointer(uip) // … convert it "unsafely" |
|||
⚫ | |||
fmt.Printf(" vp has type %-14T = %v\n", vp, vp) |
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(" up has type %-14T = %#0x\n", up, up) |
||
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) |
fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) |
||
Line 531: | Line 529: | ||
// or an incr all on one ulgy line: |
// or an incr all on one ulgy line: |
||
*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ |
*(*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: | Line 563: | ||
1: unexported int false |
1: unexported int false |
||
vp has type reflect.Value = <*int Value> |
vp has type reflect.Value = <*int Value> |
||
uip has type uintptr = 0xc208000208 |
|||
up has type unsafe.Pointer = 0xc208000208 |
up has type unsafe.Pointer = 0xc208000208 |
||
p has type *int = 0xc208000208 pointing at 42 |
p has type *int = 0xc208000208 pointing at 42 |