如何在 Python 中创建一个无符号字符数组? (对于使用 PyOpenGL 的 glReadPixels)

How to create an unsigned char array in Python? (For glReadPixels using PyOpenGL)

我已经使用 PyOpenGL 在 GLES2 和 EGL 中编写了一些代码,我需要使用 glReadPixels 函数,除了最后一个参数必须是一个 ctypes unsigned char 缓冲区,我不确定如何创建它。

这是 C 代码:

unsigned char* buffer = malloc(width * height * 4);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

等效的 Python 代码是什么?

我使用的是 GLES2 而不是 GL,因此,buffer = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE) 不起作用。

当我尝试 buffer = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE) 时,出现以下错误:

   buffer = glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE)
  File "/home/fa/berryconda3/lib/python3.6/site-packages/OpenGL/platform/baseplatform.py", line 415, in __call__
    return self( *args, **named )
TypeError: this function takes at least 7 arguments (6 given)

创建一个大小合适的字节缓冲区:

buffer_size = width * height * 4
buffer = (GLbyte * buffer_size)()

传递缓冲区 glReadPixels:

glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer)

这与使用 ctypes.c_byte 相同:

import ctypes
buffer_size = width * height * 4
buffer = (ctypes.c_byte * buffer_size)()

或者创建一个适当大小的 numpy 缓冲区:

import numpy
buffer = numpy.empty(width * height * 4, "uint8")

传递缓冲区glReadPixels:

glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer)