unix - 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    // have bytes(content), struct(record/c.utmpx)   // how can cast bytes struct ? }  func handleerror(err error) {   if err != nil {     panic("bad")   } } 

i'm trying read content record have asked few related questions.

cannot access c variables in cgo

can not read utmpx file in go

i have read articles , posts still cannot figure out way this.

i think you're going wrong way. if wanting use c library, use c library read file.

don't use cgo purely have struct definitions, should create these in go yourself. write appropriate marshal / unmarshal code read raw bytes.

a quick google shows has done work required convert of relevant c library go. see utmp repository.

a short example of how 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 {     := bytes.indexbyte(b, 0)     if == -1 {         = len(b)     }     return string(b[:i]) }  func main() {     list, err := utmp.readutmp(utmp.utmpxfile, 0)     handleerror(err)     _, u := range list {         fmt.println(bytetostr(u.user[:]))     } }  

you can view godoc utmp package more information.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -