Golang如何将struct的sizeof提取为int

时间:2019-02-25 15:43:33

标签: go int sizeof

我开始学习golang,但遇到了我希望这是一个简单的问题。

我有一个用几种结构用C编写的文件。即myStruct的 现在,我想从该文件中读取一种数据结构。

在C语言中,我简单地打开一个文件,并移动fileptr的结构数* sizeofStruct。像这样

int sizeofStruct = sizeof(myStruct)
seek(filehandle, searchNo*sizeofStruct)
read(filehandle, &data, sizeofStruct)

在Golang中,这似乎不像“ sizeof”那么简单...而是以uintptr结尾的多次转换...某物,或反射。int32()

var spect Spectrum // struct Spectrum
const SizeOfSpectrum = unsafe.Sizeof(spect)

我希望C中的SizeOfSpectrum包含等于sizeof(spect)

你们能帮助我在int变量中获取结构的大小吗?

1 个答案:

答案 0 :(得分:0)

  

我有一个用几种结构用C编写的文件。即myStruct的Now   我想从该文件读取一个数据结构。在C我简单地打开一个   文件并移动文件的结构数* sizeofStruct。

     

我还没有找到一种方法来获取数值并乘以   另一个,说int16值。目的是在   文件。


您在Go中使用显式转换执行相同的操作。

例如,

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    type S struct{ F int32 }
    i16 := int16(42)
    // The Go Programming Language Specification
    // https://golang.org/ref/spec
    // Numeric types
    // Explicit conversions are required when different
    // numeric types are mixed in an expression or assignment.
    // func (f *File) Seek(offset int64, whence int) (ret int64, err error)
    offset := int64(i16) * int64(unsafe.Sizeof(S{}))
    fmt.Println(offset)
}

游乐场:https://play.golang.org/p/YFyU11Lf2qc

输出:

168