简体   繁体   English

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

[英]How to cast bytes to struct(c struct) in go?

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. 我试图将content读入Record我问了一些相关问题。

Cannot access c variables in cgo 无法访问CGO中的C变量

Can not read utmpx file in go Go中无法读取utmpx文件

I have read some articles and posts but still cannot figure out a way to do this. 我已经阅读了一些文章和帖子,但仍然找不到解决方法。

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. 如果要使用C库,则可以使用C库读取文件。

Don't use cgo purely to have struct definitions, you should create these in Go yourself. 不要纯粹使用cgo来拥有结构定义,您应该在Go中自己创建它们。 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. 快速的Google显示,有人已经完成了将相关C库的外观转换为Go所需的工作。 See the utmp repository . 请参阅utmp信息库

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. 您可以查看utmp软件包的GoDoc以获得更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM