2017-07-26 17 views
0
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") 
    } 
} 

contentRecordに入力してください。 私はいくつかの関連する質問をしました。goでstruct(c struct)にバイトをキャストする方法は?

Cannot access c variables in cgo

Can not read utmpx file in go

私はいくつかの記事や記事を読みましたが、まだこれを行う方法を把握することはできません。

答えて

2

あなたはこれについて間違った方法をとっていると思います。 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[:])) 
    } 
} 

あなたはより多くの情報のためutmpパッケージのGoDocを表示することができます。

+0

私はこのレポを知っており、それを読んでいます。私はただ試してみたい。ご回答有難うございます。私は 'undefined:utmp.ReadUtmp'、' undefined:utmp.UtmpxFile'を得ました。 –

+0

私は他の答えがあるのを見て待っています。 –

+1

GZ Xue、utmpライブラリをインストールするために 'go get github.com/ericlagergren/go-gnulib/utmp'を実行しましたか? – Mark

関連する問題