从字符串指针golang [英] Pointers golang from string
问题描述
我的应用程序接受来自 os.Args
的指针。
$ b
pointer:= os.Args [1] //0x7ffc47e43200
如何使用该指针并获取存储在该位置的值?
免责声明:正如你可能知道的那样,这是危险的,如果你打算在生产应用程序中这样做,最好有一个很好的理由。这就是说...
你需要做一些事情。这里是代码,然后我们将通过它。
package main
import(
fmt
os
strconv
不安全
)
func main(){
str :=7ffc47e43200// strconv.ParseUint不喜欢0x前缀
u,err:= strconv.ParseUint(str,16,64)
if err!= nil {
fmt.Fprintln(os.Stderr,can not parse pointer:,err)
os.Exit(1)
}
ptr:= unsafe.Pointer(uintptr (u))//泛型指针(如C中的void *)
intptr:=(* int)(ptr)//指向int的指针
fmt.Println(* intptr)
}
你可以在 Go Playground 。
首先,我们需要将字符串解析为一个数值。在你的例子中,你给出了一个十六进制数字,所以我们将以16为基础进行解析(这是code> strconv.ParseUint 的16参数)。请注意, strconv.ParseUint
不喜欢0x前缀,所以我删除了它。
unsafe.Pointer
类型。通常,编译器不会让您在指针类型之间进行转换。例外是,根据 unsafe.Pointer
文档 :
- 任何类型的指针值都可以转换为指针。
- 指针可以转换为任何类型的指针值。
uintptr可以转换为指针。
- 指针可以转换为uintptr。
因此,为了转换为指针,需要首先转换为 uintptr
,然后转换为 unsafe.Pointer
。从这里,我们可以转换为任何我们想要的指针类型。在这个例子中,我们将转换为一个int指针,但我们也可以选择其他指针类型。然后,我们取消引用指针(在这种情况下会导致混乱)。
My application accepts a pointer from os.Args
.
For example
pointer := os.Args[1] //"0x7ffc47e43200"
How can I use that pointer and get the value that is stored on that location?
Disclaimer: As you are probably aware, this is dangerous and if you're going to do this in a production application, you'd better have a really good reason. That being said...
You need to do a few things. Here's the code, and then we'll walk through it.
package main
import (
"fmt"
"os"
"strconv"
"unsafe"
)
func main() {
str := "7ffc47e43200" // strconv.ParseUint doesn't like a "0x" prefix
u, err := strconv.ParseUint(str, 16, 64)
if err != nil {
fmt.Fprintln(os.Stderr, "could not parse pointer:", err)
os.Exit(1)
}
ptr := unsafe.Pointer(uintptr(u)) // generic pointer (like void* in C)
intptr := (*int)(ptr) // typed pointer to int
fmt.Println(*intptr)
}
You can run this on the Go Playground.
First, we need to parse the string as a numerical value. In your example, you gave a hexadecimal number, so we'll parse in base 16 (that's the "16" argument to strconv.ParseUint
). Note that strconv.ParseUint
doesn't like the "0x" prefix, so I removed it.
Then, we need to convert the number into a pointer type. For this, we will use the unsafe.Pointer
type, which is special to the Go compiler. Normally, the compiler won't let you convert between pointer types. The exception is that, according to the unsafe.Pointer
documentation:
- 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.
Thus, in order to convert to a pointer, we'll need to first convert to a uintptr
and then to an unsafe.Pointer
. From here, we can convert to any pointer type we want. In this example, we will convert to an int pointer, but we could choose any other pointer type as well. We then dereference the pointer (which panics in this case).
这篇关于从字符串指针golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!