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

标签 c unix 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")
  }
}

我正在尝试将 content 读入 Record 我问了一些相关的问题。

Cannot access c variables in cgo

Can not read utmpx file in go

我已经阅读了一些文章和帖子,但仍然想不出一种方法来做到这一点。

最佳答案

我认为你的做法是错误的。如果您想使用 C 库,则可以使用 C 库来读取文件。

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

快速谷歌显示有人已经完成了将相关 C 库的外观转换为 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 包以获取更多信息。

关于c - 如何在 go 中将字节转换为 struct(c struct)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318603/

相关文章:

c - 我不知道为什么这段代码会给我带来读取访问冲突。理论上,取消引用指针并减去另一个字符应该可行

c++ - inotify_add_watch 失败,没有这样的文件或目录

perl - 如何在Unix上的多个文件中的特定行插入一行?

go - 如何在 Go 中启用 CORS

go - 如何使用 golang 中的并行子测试处理父测试拆解

c - 如何将用户数据传递给回调函数

c - 通过 SOCKS5 代理进行 SSL 连接

Python select() 行为很奇怪

python - 如何从Linux日志文件中只获取新行?

go - golang中最灵活的函数签名