英文:
Extract uintptr from reflect.Value
问题
给定代码中的注释,你需要进行以下翻译:
- 我需要一种在这种情况下区分指针和值的方法。
- 如果
i
是指向结构体的指针,我需要将其转换为uintptr
类型。
另外,根据我目前的发现:(*reflect.Value).InterfaceData()
的第二个成员将是指向结构体的指针(如果它是结构体的话)。如果不是结构体,我不知道它是什么。
英文:
Given
// 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 need some way to distinguish between pointers and values in this situation.
- If
i
was a pointer to struct, I need to cast it touintptr
.
Something I discovered so far: the second member of the (*reflect.Value).InterfaceData()
will be the pointer to the struct, in case it is a struct. I have no idea what it is in case it is not a struct.
答案1
得分: 1
使用Pointer方法将结构体的地址作为uintptr获取:
var p uintptr
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
p = v.Pointer()
}
这段代码假设v
是调用reflect.ValueOf(i)
的结果,如问题中所示。在这种情况下,v
表示i
的元素,而不是i
本身。例如,如果接口i
包含一个int
,那么v.Kind()
是reflect.Int
,而不是reflect.Interface
。
如果v
具有接口值,则通过接口向下获取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()
}
英文:
Use the Pointer method to get the address of a struct as a uintpr:
var p uintptr
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
p = v.Pointer()
}
This code assumes that v
is the result of calling reflect.ValueOf(i)
as shown in the question. In this scenario, v
represents i
's element, not i
. For example, if interface i
contains an int
, then v.Kind()
is reflect.Int
, not reflect.Interface
.
If v
has an interface value, then drill down through the interface to get the 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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论