如何投入字节结构(C结构)在去? [英] 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;
* /
导入C
导入(
fmt
io / ioutil
)
类型Record C.utmpx
func main(){
path:= C.GoString(C.path_utmpx)
content,err:= ioutil .ReadFile(path)
handleError(err)
var records []记录
//现在我们有字节(内容),结构体(Record / C.utmpx)
//如何将字节转换为结构体?
$ b $ func handleError(错误错误){
if err!= nil {
panic(bad)
}
}
我试图将 content
读入记录
我已经提出了一些相关问题。 $ b
我已经阅读了一些文章和帖子,但仍然无法想出办法做到这一点。
我想你会以错误的方式去做。如果您想使用C库,您可以使用C库来读取文件。
不要纯粹使用cgo来创建结构定义,您应该创建这些在你自己。然后,您可以编写适当的编组/解组码来从原始字节读取。
快速Google显示有人已经完成了将相关C库外观转换为Go所需的工作。请参阅 utmp资源库。
一个简短的例子是:
包主
fmt
log
github.com/ericlagergren/go-gnulib/utmp
)
func handleError(错误错误){
if err!= nil {
log.Fatal(err)
}
}
func byteToStr(b [] byte)string {
i:= bytes.IndexByte(b,0)
if i == -1 {
i = len(b)
}
返回字符串(b [:i])
}
func main(){
list,err:= utmp.ReadUtmp(utmp.UtmpxFile, 0)
handleError(err)
for _,u:=范围列表{
fmt.Println(byteToStr(u.User [:]))
}
}
您可以查看 Go Doc 为 utmp
包获取更多信息。
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
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.
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.
这篇关于如何投入字节结构(C结构)在去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!