dongrandi8411 2017-07-26 06:03
浏览 33
已采纳

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

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")
  }
}

I'm trying to read content into Record I have asked a few related questions.

Cannot access c variables in cgo

Can not read utmpx file in go

I have read some articles and posts but still cannot figure out a way to do this.

  • 写回答

1条回答 默认 最新

  • duanchong3075 2017-07-26 08:39
    关注

    I think you're going about this the wrong way. If you were wanting to use the C library, you would use the C library to read the file.

    Don't use cgo purely to have struct definitions, you should create these in Go yourself. You could then write the appropriate marshal / unmarshal code to read from the raw bytes.

    A quick Google shows that someone has already done the work required to convert a look of the relevant C library to Go. See the utmp repository.

    A short example of how this could be used is:

    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[:]))
        }
    } 
    

    You can view the GoDoc for the utmp package for more information.

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改