What is the canonical way to deal with CGo functions that expect size in memory in bytes?

StackOverflow https://stackoverflow.com/questions/18678050

  •  28-06-2022
  •  | 
  •  

質問

I'm playing around with OpenGL and Go. It's mostly pretty intuitive, but there is a few awkward interface problems. The second argument of glBufferData should be the size of the buffer in memory.

C.glBufferData(C.GLenum(target), C.GLsizeiptr(size), ptr(data), C.GLenum(usage))

In the case that the buffer contains 32 bit floats each element will take of 4 bytes, so for the second argument I can do something like:

sizeofFloat := 4
size := sizeofFloat * len(buffer)
C.glBufferData(C.GLenum(target), C.GLsizeiptr(size), ptr(data), C.GLenum(usage))

Is there a better way to get the size of a type in memory other than just hard coding it?

役に立ちましたか?

解決

You can use unsafe.Sizeof for that:

This is the easiest since you're already using "unsafe" logic anyway. Otherwise, you might use reflect.Type's Size method for that, to avoid importing unsafe:

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top