【发布时间】:2013-08-19 16:45:33
【问题描述】:
我目前正在编写代码以从 NSView 获取 OpenGL 纹理。该代码主要是 Apple 示例代码。但是,我需要在 C++ 类中使用它,并且有泄漏对象的问题。
这是代码中有趣的部分:
GLuint CPlusPlusClass::openGLTexFromNSView(NSView* theView)
{
GLuint texName = 0x0;
@autoreleasepool // 1
{ // 1
NSBitmapImageRep* bitmap = [theView bitmapImageRepForCachingDisplayInRect:[theView visibleRect]];
int samplesPerPixel = 0;
[theView cacheDisplayInRect:[theView visibleRect] toBitmapImageRep:bitmap];
samplesPerPixel = (int)[bitmap samplesPerPixel];
glPixelStorei(GL_UNPACK_ROW_LENGTH, (int)([bitmap bytesPerRow]/samplesPerPixel));
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
glGenTextures (1, &texName);
glBindTexture (GL_TEXTURE_RECTANGLE_ARB, texName);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
if(![bitmap isPlanar] && (samplesPerPixel == 3 || samplesPerPixel == 4))
{
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0,
samplesPerPixel == 4 ? GL_RGBA8 : GL_RGB8,
(int)[bitmap pixelsWide], (int)[bitmap pixelsHigh],
0, samplesPerPixel == 4 ? GL_RGBA : GL_RGB,
GL_UNSIGNED_BYTE, [bitmap bitmapData]);
}
} // 1
return texName;
}
当我将视图绘制到 OpenGL 上下文并在 Activity Monitor 中检查应用程序的内存占用时,我看到每次 Activity Monitor 的视图刷新时,该数字都会增加大约 4 MB。通过在代码中添加由//1 指示的@autoreleasepool 块,我可以将它降低到每个刷新周期大约2 MB。尽管如此,它仍在不断增加。
从 C++ 中释放自动释放对象的正确方法是什么?
【问题讨论】:
标签: objective-c opengl objective-c++ autorelease