| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package unsafe2 |
| 6 |
|
| 7 |
import ( |
| 8 |
"reflect" |
| 9 |
"unsafe" |
| 10 |
) |
| 11 |
|
| 12 |
type dummy struct{} |
| 13 |
|
| 14 |
|
| 15 |
var DummyType = reflect.TypeOf(dummy{}) |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
type rtype struct { |
| 20 |
_ uintptr |
| 21 |
_ uintptr |
| 22 |
_ uint32 |
| 23 |
_ uint32 |
| 24 |
_ uintptr |
| 25 |
_ uintptr |
| 26 |
_ uint32 |
| 27 |
_ uint32 |
| 28 |
} |
| 29 |
|
| 30 |
type emptyInterface struct { |
| 31 |
typ *rtype |
| 32 |
_ unsafe.Pointer |
| 33 |
} |
| 34 |
|
| 35 |
type structField struct { |
| 36 |
_ uintptr |
| 37 |
typ *rtype |
| 38 |
_ uintptr |
| 39 |
} |
| 40 |
|
| 41 |
type structType struct { |
| 42 |
rtype |
| 43 |
_ uintptr |
| 44 |
fields []structField |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
func SetFieldType(s reflect.Type, idx int, t reflect.Type) { |
| 51 |
if s.Kind() != reflect.Struct || idx >= s.NumField() { |
| 52 |
return |
| 53 |
} |
| 54 |
|
| 55 |
rtyp := unpackType(s) |
| 56 |
styp := (*structType)(unsafe.Pointer(rtyp)) |
| 57 |
f := styp.fields[idx] |
| 58 |
f.typ = unpackType(t) |
| 59 |
styp.fields[idx] = f |
| 60 |
} |
| 61 |
|
| 62 |
func unpackType(t reflect.Type) *rtype { |
| 63 |
v := reflect.New(t).Elem().Interface() |
| 64 |
return (*emptyInterface)(unsafe.Pointer(&v)).typ |
| 65 |
} |