英文:
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.Type
的Size
方法来实现,以避免导入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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论