处理期望以字节为单位的CGo函数的规范方法是什么?

huangapple go评论77阅读模式
英文:

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

问题

我正在玩OpenGL和Go。它大部分都很直观,但有一些界面问题比较尴尬。glBufferData的第二个参数应该是内存缓冲区的大小。

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

如果缓冲区包含32位浮点数,每个元素将占用4个字节,所以对于第二个参数,我可以这样做:

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

有没有比硬编码更好的方法来获取类型在内存中的大小?

英文:

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?

答案1

得分: 2

你可以使用unsafe.Sizeof来实现:

这是最简单的方法,因为你已经在使用"unsafe"逻辑了。否则,你可以使用reflect.TypeSize方法来实现,以避免导入unsafe

英文:

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:

huangapple
  • 本文由 发表于 2013年9月8日 05:25:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/18678050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定