dongtun1209 2013-02-04 23:40
浏览 136
已采纳

切片内容的大小(以字节为单位)

I am trying to send some data to OpenGl. Sending an array is easy thanks to Sizeof:

array := [...]Whatever {lots of data}
array_ptr := gl.Pointer(&array[0])
array_size := gl.Sizeiptr(unsafe.Sizeof(array))
gl.BufferData(gl.ARRAY_BUFFER, array_size, array_ptr, gl.STATIC_DRAW)

I would like to use slices instead of arrays because the size of my 3D models is not known at compile time.

How do I retrieve the size, in bytes, of the content of a slice? I thought of this:

size := uintptr(len(slice)) * unsafe.Sizeof(slice[0])

but it is not very general. Indeed, I need to know the underlying type of the slice in order for this to work, and this supposes that all the elements of the array have the same size.

I could also loop over the whole slice and add all the sizes of every element. It's not very fast.

I am ready to always keep the len(s)==cap(s), can that help me?

Edit: implementation of the proposed solution using runtime reflection

package main

import "fmt"
import "reflect"

func ElemSize(container interface{}) uintptr {
    return reflect.TypeOf(container).Elem().Size()
}
func ElemSizeVerbose(container interface{}) uintptr {
    t := reflect.TypeOf(container)
    e := t.Elem()
    s := e.Size()
    fmt.Println(t, e, s)
    return s
}
func main() {
    a := [...]int8{2, 3, 5, 7, 11} // Array
    s := []int64{2, 3, 5, 7, 11} // Slice
    z := []int32{} // Even empty things
    ElemSizeVerbose(a) // [5]int8 int8 1
    ElemSizeVerbose(s) // []int64 int64 8
    ElemSizeVerbose(z) // []int32 int32 4
}
  • 写回答

2条回答 默认 最新

  • dongting3135 2013-02-05 01:29
    关注

    In a slice or array, every element is always the same size. Therefore, your example will work as long as len(s) > 0. In other words, as long as the slice has at least one element in it. Otherwise it will panic.

    To avoid the need of having an element in the slice, I recommend using the following:

     uintptr(len(s)) * reflect.TypeOf(s).Elem().Size()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算