从 reflect.Value 中提取 uintptr。

huangapple go评论78阅读模式
英文:

Extract uintptr from reflect.Value

问题

给定代码中的注释,你需要进行以下翻译:

  1. 我需要一种在这种情况下区分指针和值的方法。
  2. 如果 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 = ???
}
  1. I need some way to distinguish between pointers and values in this situation.
  2. If i was a pointer to struct, I need to cast it to uintptr.

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()
}

playground示例

这段代码假设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()
}

playground示例

英文:

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()
}

playground example

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()
}

playground example

huangapple
  • 本文由 发表于 2017年3月6日 17:25:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/42621848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定