我在使用 pyopengl 及其导入时遇到了一个奇怪的问题,下面是从一个更大的测试程序中截取的一个小测试程序,但这足以说明问题所在。你需要安装 PyOpenGL,如果你按原样运行它,它会显示一个空白窗口,如果你单击并拖动它,它会打印出一些 0。如果您取消注释下面的 HANDLE.final = True 行,它将停止工作,请参见下面的回溯。
from OpenGL.GL import *
from OpenGL.GLUT import *
from ctypes import POINTER
import sys
HANDLE = POINTER(None)
#HANDLE.final = True
def display():
glutSwapBuffers()
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(400,400)
glutCreateWindow("GLUT Window")
glutDisplayFunc(display)
def readPx(x,y):
data_all = glReadPixels(x, y, 1, 1, GL_RGB, GL_BYTE)
print data_all
glutMotionFunc(readPx)
glutMainLoop()
在取消注释该行的情况下,它会执行以下操作:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\OpenGL\GLUT\special.py", line 130, in safeCall
return function( *args, **named )
File "C:\Users\Robin\dev\ogl_bug\ogl_bug.py", line 19, in readPx
data_all = glReadPixels(x, y, 1, 1, GL_RGB, GL_BYTE)
File "C:\Python27\lib\site-packages\OpenGL\GL\images.py", line 371, in glReadPixels
imageData
File "C:\Python27\lib\site-packages\OpenGL\platform\baseplatform.py", line 402, in __call__
return self( *args, **named )
ArgumentError: argument 7: <type 'exceptions.TypeError'>: wrong type
GLUT Motion callback <function readPx at 0x02CC5830> with (238, 190),{} failed: returning None argument 7: <type 'exceptions.TypeError'>: wrong type
在我更大的程序中,当尝试导入 OpenGL.raw.WGL._types 时,此 HANDLE 代码被深埋了 5 或 6 个导入,它由任何 WGL Opengl 扩展导入,但这是仍然导致错误的最小片段。
我不明白为什么这条线的存在会对看似无关的 gl 调用产生影响——我如何在不破坏 PyOpenGL 的其他部分的情况下使用加载此扩展?
请您参考如下方法:
我找到了原因 - POINTER(None) 返回 ctypes.c_void_p,这是一个单例,意味着 .final 属性在此导入后全局可见,可能会在以后破坏某些类型检查机制。
在PyopenGL的github版本中已经修复。这是提交:
https://github.com/mcfletch/pyopengl/commit/f087200406a37fc4b99eaad701d18bc64ded2d71
您可以通过在任何 OpenGL 扩展之前导入这个小模块来在当前版本的 PyOpenGL 中修复它:
import OpenGL.raw.WGL._types as t
from ctypes import _SimpleCData, _check_size
delattr(t.HANDLE, "final")
class HANDLE(_SimpleCData):
_type_ = "P"
_check_size(HANDLE)
HANDLE.final = True
t.HANDLE = HANDLE
t.HGLRC = HANDLE
t.HDC = HANDLE
t.HPBUFFERARB = HANDLE
t.HPBUFFEREXT = HANDLE
这会导入导致问题的 PyOpenGL 模块,取消对 c_void_p 的损坏,然后将 HANDLE 变量及其别名重新分配给 _SimpleCData 来自上面 github 链接的解决方案。
