Search code examples
opengld

returning opengl display callback in D


I've written a simple hello world opengl program in D, using the converted gl headers here.

My code so far:

import std.string;
import c.gl.glut;

Display_callback display()
{
    return Display_callback // line 7
    {
        return; // just display a blank window
    };
} // line 10

void main(string[] args)
{
    glutInit(args.length, args);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(800,600);
    glutCreateWindow("Hello World");
    glutDisplayFunc(display);
    glutMainLoop();
}

My problem is with the display() function. glutDisplayFunc() expects a function that returns a Display_callback, which is typedef'd as typedef GLvoid function() Display_callback;. When I try to compile, dmd says

line 7: found '{' when expecting ';' following return statement
line 10: unrecognized declaration

How do I properly return the Display_callback here? Also, how do I change D strings and string literals into char*? My calls to glutInit and glutCreateWindow don't like the D strings they're getting. Thanks for your help.


Solution

  • You can't use nested functions or methods as function types, since they rely on contextual information being available (the stack or the object, respectively). You'll have to use a static or file scope function:

    void displayEmptyWindow () {
        return;
    }
    
    Display_callback display() {
        return &displayEmptyWindow;
    }
    

    EDIT: If you're using D2, you can convert a string into a C string with code such as the following:

    string str = "test string";
    
    // add one for the required NUL terminator for C
    char[] mutableString = new char[str.length + 1];
    mutableString[] = str[];
    mutableString[str.length] = '\0';
    
    // and, finally, get a pointer to the contents of the array
    char* cString = mutableString.ptr;
    

    If you know for sure that the function you're calling won't modify the string, you can simplify this a bit:

    someCFunction(cast(char*)toStringz(str));