代码之家  ›  专栏  ›  技术社区  ›  divflex

如何在go中将字节转换为struct(c struct)?

  •  0
  • divflex  · 技术社区  · 9 年前
    package main
    
    /*
    #define _GNU_SOURCE 1
    #include <stdio.h>
    #include <stdlib.h>
    #include <utmpx.h>
    #include <fcntl.h>
    #include <unistd.h>
    
    char *path_utmpx = _PATH_UTMPX;
    
    typedef struct utmpx utmpx;
    */
    import "C"
    import (
      "fmt"
      "io/ioutil"
    )
    
    type Record C.utmpx
    
    func main() {
    
      path := C.GoString(C.path_utmpx)
    
      content, err := ioutil.ReadFile(path)
      handleError(err)
    
      var records []Record
    
      // now we have the bytes(content), the struct(Record/C.utmpx)
      // how can I cast bytes to struct ?
    }
    
    func handleError(err error) {
      if err != nil {
        panic("bad")
      }
    }
    

    我在看书 content 进入 Record

    Cannot access c variables in cgo

    Can not read utmpx file in go

    我读了一些文章和帖子,但仍然无法找到一种方法来做到这一点。

    1 回复  |  直到 9 年前
        1
  •  2
  •   Martin Campbell    9 年前

    不要纯粹使用cgo来创建结构定义,您应该在Go中自己创建这些定义。然后,您可以编写适当的封送/解封代码来读取原始字节。

    utmp repository

    如何使用的一个简短示例是:

    package main
    
    import (
        "bytes"
        "fmt"
        "log"
    
        "github.com/ericlagergren/go-gnulib/utmp"
    )
    
    func handleError(err error) {
        if err != nil {
            log.Fatal(err)
        }
    }
    
    func byteToStr(b []byte) string {
        i := bytes.IndexByte(b, 0)
        if i == -1 {
            i = len(b)
        }
        return string(b[:i])
    }
    
    func main() {
        list, err := utmp.ReadUtmp(utmp.UtmpxFile, 0)
        handleError(err)
        for _, u := range list {
            fmt.Println(byteToStr(u.User[:]))
        }
    } 
    

    您可以查看 GoDoc utmp 软件包以获取更多信息。