给定
// I know that behind SomeInterface can hide either int or a pointer to struct
// In the real code I only have v, not i
i := something.(SomeInterface)
v := reflect.ValueOf(i)
var p uintptr
if "i is a pointer to struct" {
p = ???
}
- 在这种情况下,我需要一些方法来区分指针和值。
- 如果
i
是指向结构的指针,我需要将其转换为uintptr
。
到目前为止我发现了一些事情:(*reflect.Value).InterfaceData()
的第二个成员将是指向该结构的指针,如果它是一个结构的话。如果它不是结构,我不知道它是什么。
最佳答案
使用 Pointer获取结构地址作为 uintpr 的方法:
var p uintptr
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
p = v.Pointer()
}
此代码假定 v
是调用 reflect.ValueOf(i)
的结果,如问题中所示。在这种情况下,v
表示 i
的元素,而不是 i
。例如,如果接口(interface) i
包含一个 int
,那么 v.Kind()
是 reflect.Int
,而不是reflect.Interface
.
如果v
有接口(interface)值,则通过接口(interface)向下钻取得到uintptr:
if v.Kind() == reflect.Interface {
v = v.Elem()
}
var p uintptr
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
p = v.Pointer()
}
关于pointers - 从 reflect.Value 中提取 uintptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42621848/