How can I convert type uintptr to *string?

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

How can I convert type uintptr to *string?

问题

我正在尝试将 uintptr 转换为 *string,但目前似乎无法成功。我以 uintptr 的形式获取该值,并需要将其作为 *string 传递。

我尝试了以下方法:

如果 x 是 uintptr,y 是 *string

y = string(x)

  • 无法将类型为 string 的 string(x) 用作类型为 *string 的赋值

y = *string(x)

  • 无法间接引用 string(x)(类型为 string 的值)

*y = string(x)

  • uintptr 转换为 string 会产生一个字符的字符串,而不是数字的字符串(你是否意味着 fmt.Sprint(x)?)
英文:

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)?)

答案1

得分: 2

你必须使用unsafe.Pointeruintptr转换为Go指针值。

示例代码如下:

import (
	"fmt"
	"unsafe"
)

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

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

输出结果为:

0x1

请阅读unsafe和特别是unsafe.Pointer的文档,以确保正确使用。

Pointer表示对任意类型的指针。对于类型Pointer,有四个特殊操作是其他类型不具备的:

  • 任何类型的指针值都可以转换为Pointer。
  • Pointer可以转换为任何类型的指针值。
  • uintptr可以转换为Pointer。
  • Pointer可以转换为uintptr。

因此,Pointer允许程序绕过类型系统读取和写入任意内存。它应该非常小心地使用。

以下是一些有效的使用Pointer的模式。不使用这些模式的代码可能在当前环境下无效,或者在将来变得无效。即使是下面的有效模式也有重要的注意事项。

[ ... ]

英文:

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.
>
> [ ... ]

huangapple
  • 本文由 发表于 2022年11月10日 11:07:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/74383720.html
匿名

发表评论

匿名网友

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

确定