Created
August 15, 2016 15:32
-
-
Save skoowoo/8694d6212990e4fe8b25da292f64745c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"reflect" | |
"unsafe" | |
) | |
type TestStruct struct { | |
A int | |
B string | |
} | |
var ( | |
slice []byte | |
typ reflect.Type | |
) | |
func init() { | |
slice = make([]byte, 1000) | |
typ = reflect.TypeOf(TestStruct{}) | |
} | |
func main() { | |
p := (*reflect.SliceHeader)(unsafe.Pointer(&slice)) | |
buf := p.Data | |
value := reflect.NewAt(typ, unsafe.Pointer(buf)) | |
// 赋值 | |
test := value.Interface().(*TestStruct) | |
test.A = 1234 | |
test.B = "aaa" | |
// 验证是否写入到 buf 内存 | |
testBuf := (*TestStruct)(unsafe.Pointer(buf)) | |
println(test.A, test.B) | |
println(testBuf.A, testBuf.B) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment