Go uintptr from interface{}
June 28th, 2013
No comments
Some C functions accept more than one type of struct, so I wanted a Go wrapper able to pass a uintptr derived from an interface{}. Go’s reflect package makes this easy:
package main import ( "fmt" "reflect" ) type USN_JOURNAL_DATA struct { UsnJournalID int FirstUsn uint32 NextUsn uint32 LowestValidUsn uint32 MaxUsn uint32 MaximumSize uint32 AllocationDelta uint32 } func doitA(ujd *USN_JOURNAL_DATA) (size uintptr, align int, p uintptr) { v := reflect.ValueOf(ujd) t := v.Elem().Type() size = t.Size() align = t.Align() p = v.Pointer() return } func doitB(i interface{}) (size uintptr, align int, p uintptr) { v := reflect.ValueOf(i) t := v.Elem().Type() size = t.Size() align = t.Align() p = v.Pointer() return } func main() { a := USN_JOURNAL_DATA{1, 2, 3, 4, 5, 6, 7} size, align, p := doitA(&a) fmt.Println(size, align, p) size, align, p = doitB(&a) fmt.Println(size, align, p) }
Interestingly, as demonstrated above, the same implementation can be used for a func accepting either a struct pointer or an interface{}.
Recent Comments