How can I convert type uintptr to *string?

Issue

I’m trying to make a conversion from uintptr to *string that doesn’t seem to be working so far. I get the value as uintptr and need to pass it on as a *string.
The value I’m working represents an address in the file directory

here’s what I’ve tried so far:

if x is uintptr
and y is *string

y = string(x)

  • cannot use string(x) (value of type string) as type *string in assignment

y = *string(x)

  • cannot indirect string(x) (value of type string)

*y = string(x)

  • conversion from uintptr to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)

Solution

You must use unsafe.Pointer to turn a uintptr into a Go pointer value.

Example:

import (
    "fmt"
    "unsafe"
)

func main() {
    var s *string
    var p uintptr = 1

    s = (*string)(unsafe.Pointer(p))
    fmt.Println(s)
}

Output:

0x1

Read the documentation of unsafe and particularly unsafe.Pointer to ensure correct usage.

Pointer represents a pointer to an arbitrary type. There are four special operations available for type Pointer that are not available for other types:

  • A pointer value of any type can be converted to a Pointer.
  • A Pointer can be converted to a pointer value of any type.
  • A uintptr can be converted to a Pointer.
  • A Pointer can be converted to a uintptr.

Pointer therefore allows a program to defeat the type system and read and write arbitrary memory. It should be used with extreme care.

The following patterns involving Pointer are valid. Code not using these patterns is likely to be invalid today or to become invalid in the future. Even the valid patterns below come with important caveats.

[ … ]

Answered By – Hymns For Disco

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.