英文:
Casting a int to a pointer?
问题
在C/C++中,可以像这样将int转换为int*:
int i = 0x1040c108;
int *p = (int*)i; // 编译通过
但是为什么在Go语言中不能这样做呢?
addr := 0x1040c108
p := (*int)(addr) // 错误:无法将addr(类型为int)转换为*int类型
在Go语言中,不能直接将整数转换为指针类型。要实现类似的功能,可以使用unsafe包中的函数来进行指针操作。下面是在Go语言中实现类似功能的方式:
import "unsafe"
addr := 0x1040c108
p := (*int)(unsafe.Pointer(uintptr(addr)))
需要注意的是,使用unsafe包进行指针操作是不安全的,因为它绕过了Go语言的类型系统和内存安全检查。在使用时要谨慎,并确保了解相关的风险和限制。
英文:
in C/C++ I can cast int to a int* like this
int i = 0x1040c108;
int *p = (int*)i; // compiles
but why can't I do this in Go?
addr := 0x1040c108
p := (*int)(addr) // Error: cannot convert addr (type int) to type *int
What is the way to achieve this in golang ??
答案1
得分: 2
请注意,unsafe包被称为"unsafe"是有原因的,除非你真的需要绕过类型安全或直接操作内存,否则不应使用它。
package main
import (
	"fmt"
	"unsafe"
)
func main() {
	fmt.Println("Hello, playground")
	var intaddr int = 0x1040c108
	var addr uintptr = uintptr(intaddr)
	ptr := unsafe.Pointer(addr)
	p := (*int)(ptr)
	fmt.Printf("Type: %T, Ptr: %v, Val: %d", p, p, *p)
}
请通过unsafe包进行操作。
英文:
Go through the unsafe package. Please note that it is called "unsafe" for a reason and probably shouldn't be used unless you REALLY need to do operations that bypass type safeties, or operate on memory directly.
https://play.golang.org/p/WUavNAlyVP
package main
import (
	"fmt"
	"unsafe"
)
func main() {
	fmt.Println("Hello, playground")
	var intaddr int = 0x1040c108
	var addr uintptr = uintptr(intaddr)
	ptr := unsafe.Pointer(addr)
	p := (*int)(ptr)
	fmt.Printf("Type: %T, Ptr: %v, Val: %d", p, p, *p)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论