Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a type uintptr to uint64 in Golang

I'm trying to assign the value found in a variable of type uintptr to a uint64 variable in Go. Using

myVar = valFromSystem

gives me

cannot use valFromSystem (type uintptr) as type uint64 in assignment

And trying

myVar = *valFromSystem

gives me

invalid indirect of valFromSystem (type uintptr)

Is there a way to pull the value pointed to by valFromSystem to assign to myVar?

like image 389
Bart Silverstrim Avatar asked Apr 21 '14 17:04

Bart Silverstrim


1 Answers

First, cast valFromSystem into an unsafe.Pointer. An unsafe.Pointer can be casted into any pointer type. Next, cast the unsafe.Pointer into a pointer to whatever type of data valFromSystem points to, e.g. an uint64.

ptrFromSystem = (*uint64)(unsafe.Pointer(valFromSystem))

If you just want to get the value of the pointer (without dereferencing it), you can use a direct cast:

uint64FromSystem = uint64(valFromSystem)

Though remember that you should use the type uintptr when using pointers as integers.

like image 125
fuz Avatar answered Sep 17 '22 11:09

fuz