Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass String as GLchar** (char**) parameter in glShaderSource?

Tags:

swift

opengl

I have shader that stored in a String value:

    var myShader = 
    "    attribute vec4 a_position;" +
    "    void main() {" +
    "    gl_Position = a_position;" +
    "    }"

    glShaderSource(shader, GLsizei(1), myShader, nil)

The function glShaderSource has the bind signature:

    func glShaderSource(shader: GLuint, count: GLsizei, string: UnsafePointer<UnsafePointer<GLchar>>, length: UnsafePointer<GLint>)

When I try to pass the shader String to glShaderSource directly I get the error message:

    'String' is not convertible to 'UnsafePointer<UnsafePointer<GLchar>>'

How to pass String correctly? (xCode Version 6.1 (6A1052d))

like image 651
Denis Kreshikhin Avatar asked Dec 14 '14 05:12

Denis Kreshikhin


3 Answers

Swift 3:

let shaderStringUTF8 = shaderString.cString(using: String.defaultCStringEncoding)
var shaderStringUTF8Pointer = UnsafePointer<GLchar>(shaderStringUTF8)

glShaderSource(shaderHandle, GLsizei(1), &shaderStringUTF8Pointer, nil)
like image 148
theancientchild Avatar answered Nov 06 '22 05:11

theancientchild


After half day search I found the work solution without compilation erros and bad memory access fails:

var cStringSource = (code as NSString).UTF8String
glShaderSource(shader, GLsizei(1), &cStringSource, nil)
like image 12
Denis Kreshikhin Avatar answered Nov 06 '22 05:11

Denis Kreshikhin


CLchar is typealiased as a CChar in OpenGLs Swift implementation. Make the conversion like this:

var shaderString: String = "here's a String"
let cstring = shaderString.cStringUsingEncoding(NSUTF8StringEncoding)
glShaderSource(shader, GLsizei(1), UnsafePointer(cstring), nil)
like image 2
Sean Avatar answered Nov 06 '22 04:11

Sean