【问题标题】:Function that expects an UnsafeMutablePointer<Type>!需要 UnsafeMutablePointer<Type> 的函数!
【发布时间】:2017-02-25 09:35:53
【问题描述】:

我正在尝试在Apple documentation(用 Objective-C 编写)之后使用 OpenGL 渲染屏幕外图像。我创建了一个简单的 Cocoa CLI 项目,并将此代码作为入门添加到 main.swift 文件中,但我无法编译它:

import Foundation
import AGL

var framebuffer: GLuint

glGenFramebuffersEXT(1, &framebuffer)

使用此代码,我从编译器收到以下消息:Address of variable 'framebuffer' taken before it is initialized

OpenGL 函数的签名是func glGenFramebuffersEXT(_ n: GLsizei, _ framebuffers: UnsafeMutablePointer&lt;GLuint&gt;!)

当尝试使用var framebuffer: GLuint = 0 时,程序会崩溃。

我应该如何初始化 framebuffervariable 以使其工作?

【问题讨论】:

  • var framebuffer: GLuint = 0 将是正确的方法,就类型系统而言。我对函数了解不够,无法知道它期望什么样的值

标签: swift cocoa opengl


【解决方案1】:

所有 OpenGL API 都需要在特定的 OpenGL 渲染上下文中运行。 我没有在 macOS 上尝试过多使用 OpenGL,但是这段代码运行时不会崩溃:

import OpenGL.GL
import AppKit

let attributes: [NSOpenGLPixelFormatAttribute] = [
    NSOpenGLPFAAllRenderers,
    NSOpenGLPFAAllowOfflineRenderers,
    //...
    0 //terminator
].map{NSOpenGLPixelFormatAttribute($0)}
if
    let format = NSOpenGLPixelFormat(attributes: attributes),
    let context = NSOpenGLContext(format: format, share: nil)
{
    context.makeCurrentContext()

    var framebuffer: GLuint = 0 //<- this is the right way to work with `UnsafeMutablePointer<GLuint>`.
    glGenFramebuffers(1, &framebuffer)
    //...
}

【讨论】:

  • 你说得对,我误解了文档,认为屏幕外渲染不需要渲染上下文。
  • @iamdto,其实苹果的文档我已经重读了好几遍了,还不够清楚,即使我们做离屏渲染也需要一些渲染上下文。而且还不清楚创建屏幕外渲染上下文的最佳方法是什么。最好使用 Apple 的 Bug Reporter 编写改进请求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 2019-06-23
相关资源
最近更新 更多