1

Language: D
Library: DerelictGL3

I'm trying to call glShaderSource( GLuint,GLsizei,const( GLchar* )*,const( GLint )* ) from D

I have the shader source in a string and the shader id for the first argument.

What I'm having problems with is the syntax for the last 3 arguments, all I've managed to get are compiler errors. I don't know how to go from the string containing the shader's source to what I need for the last 3 arguments, particularly the 3rd argument const( GLchar* )*
I'm looking for example code that does this along with explanation on what the code is doing, to go from the string to what ever is needed for the last 3 arguments.

2 Answers2

1

You'll need to convert the D string to a C zero terminated char*:

immutable(char*) sourceC = toStringz(vertexShaderSource);
glShaderSource(vertexShaderId, 1, &sourceC, null);

The last parameter can be null, because then it will treat the string as zero terminated. See the documentation: https://www.opengl.org/sdk/docs/man/html/glShaderSource.xhtml

The third parameter is actually supposed to be an array of strings, that's why it's const(char*)*. In C, a pointer can be used to simulate an array like this.

user1431317
  • 2,674
  • 1
  • 21
  • 18
  • 1
    Had to do" immutable(char*) sourceC = toStringz(vertexShaderSource); glShaderSource(vertexShaderId, 1, &sourceC, null);" in order to get the compiler to actually compile – chainingsolid Mar 25 '16 at 20:51
  • I've edited my answer with the correct version in case someone finds it in the future. – user1431317 Mar 25 '16 at 20:54
1

glShaderSource takes an array of character arrays, and an array of lengths of those character arrays.

I use "character arrays" because they are definitely not D strings (aka immutable(char)[]s, which itself is a tuple of a pointer and a length), and they're not quite C strings (which must be null terminated; the size parameter lets you do otherwise).

Now, you could convert the D strings into C strings with toStringz, but that does an unnecessary allocation. You can instead pass the data in the D strings directly:

// Get the pointer to the shader source data, and put it in a 1-sized fixed array
const(char)*[1] shaderStrings = [vertexShaderSource.ptr];
// Same but with shader source length
GLint[1] shaderSizes = [vertexShaderSource.length];
// Pass arrays to glShaderSource
glShaderSource(vertexShaderID, shaderStrings.length, shaderStrings.ptr, shaderSizes.ptr);
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85