dtyz76562 2018-10-19 23:30
浏览 63
已采纳

获取存储在地址中的值

I'm starting to learn GO and would like for someone to help me understand something. How can I read the value at address that is returned by syscall.GetcomputerName? I understand that that call will store the address in variable y. Thank you

package main

import "fmt"

import "syscall"
import "os"

func main() {
    x, err := os.Hostname()
    y := syscall.GetComputerName
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(x)
    fmt.Println(y)

}
  • 写回答

1条回答 默认 最新

  • douxun4173 2018-10-20 01:00
    关注

    syscall.GetComputerName is the address of the function. To execute the syscall.GetComputerName function use the function call operator (). For example, on Windows,

    package main
    
    import (
        "fmt"
        "syscall"
        "unicode/utf16"
    )
    
    func ComputerName() (name string, err error) {
        var n uint32 = syscall.MAX_COMPUTERNAME_LENGTH + 1
        b := make([]uint16, n)
        e := syscall.GetComputerName(&b[0], &n)
        if e != nil {
            return "", e
        }
        return string(utf16.Decode(b[0:n])), nil
    }
    
    func main() {
        name, err := ComputerName()
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println("ComputerName:", name)
    }
    

    Output:

    ComputerName: PETER
    

    Microsoft: GetComputerNameW

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?