duanfen9090 2017-05-03 18:51 采纳率: 100%
浏览 449
已采纳

将整数转换为指针?

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条回答 默认 最新

  • doupao1530 2017-05-03 19:06
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥21 matlab怎么求时域信号的二阶导数
  • ¥15 判断两个表是否完全相同
  • ¥15 java map类型数据格式,如何快速通过前缀匹配元素
  • ¥15 stc12c5a60s2、QMC5883L、LCD1602组合测量磁场所需程序
  • ¥20 Win11测试yolov4,“找不到nvcuda.dll”怎么办?
  • ¥15 simulink绘制bode图
  • ¥15 php_network_getaddresses: getaddrinfo failed: Name or service not known
  • ¥15 用msg发消息出现的问题
  • ¥15 unity3d机械臂
  • ¥20 工控机出现散热器转一下停一下这种情况,是什么原因造成的