Roc Altair
Roc Altair

Reputation: 11

How to convert unsafe.Pointer to reflect.Type or reflect.Value

I got one variable's address which type is converted to unsafe.Pointer, and I got its type name, such as "int64" or "struct main.Person" or others.

see the code:

package main

type Person struct {
    Name string
    Age int
}

p := Person{"john", 25}
addr := unsafe.Pointer(&p)
typName := "struct main.Person"

typ := module.TypeOfByAddr(addr, typName)

// now, I got variable addr, typName in func module.TypeOfByAddr
// how can I get reflect.Type of variable p without using package.Person to convert?

package module

func TypeOfByAddr(addr unsafe.Pointer, typName string) reflect.Type {
    // how to convert addr to reflect.Type?
}

Upvotes: 1

Views: 2972

Answers (1)

ANisus
ANisus

Reputation: 78075

Why would you need the pointer to get the Type? All you need is the type name.

In Go, it is not possible to get the reflect.Type from a string directly. The type must be referenced somewhere in order for the compiler to know it is to be included. However, you can get the same effect using map[string]reflect.Type.

If your types are static, just declare:

var types = map[string]reflect.Type{
    "int64": reflect.TypeOf(int64(0)),
    "string": reflect.TypeOf(string("")),
    // ... and so on
}

If your types are registered dynamically from different packages, you can register your types from init functions like this:

var types = make(map[string]reflect.Type)

func AddType(name string, i interface{}) {
    if _, ok := types[name]; ok {
        panic("Type " + name + " registered multiple times")
    }
    types[name] = reflect.TypeOf(i)
}

// Called somewhere else

func init() {
    AddType("struct main.Person", Person{})
}

If you want to get the reflect.Value from a pointer and a type name, you can do the following:

func ValueOfByAddr(addr unsafe.Pointer, typName string) reflect.Value {
    t, ok := types[typName]
    if !ok {
        panic("Unknown type name")
    }
    return reflect.NewAt(t, addr)
}

Upvotes: 1

Related Questions