在D中返回opengl显示回调

时间:2010-12-25 04:12:41

标签: opengl d

我在D中编写了一个简单的hello world opengl程序,使用转换后的gl标头here

到目前为止我的代码:

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();
}

我的问题在于display()功能。 glutDisplayFunc()需要一个返回Display_callback的函数,该函数的类型定义为typedef GLvoid function() Display_callback;。当我尝试编译时,dmd说

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

如何在此处正确返回Display_callback?另外,如何将D字符串和字符串文字更改为char*?我对glutInitglutCreateWindow的来电不喜欢他们获得的D字符串。谢谢你的帮助。

2 个答案:

答案 0 :(得分:3)

您不能将嵌套函数或方法用作函数类型,因为它们依赖于可用的上下文信息(分别是堆栈或对象)。您必须使用静态或文件范围功能:

void displayEmptyWindow () {
    return;
}

Display_callback display() {
    return &displayEmptyWindow;
}

编辑:如果您使用的是D2,则可以使用以下代码将字符串转换为C字符串:

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;

如果你确定你正在调用的函数不会修改字符串,你可以稍微简化一下:

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

答案 1 :(得分:0)

glutDisplayFunc()期望一个不带参数的函数返回GLvoid(即什么都没有)。你引用的typedef是创建一个名为Display_callback的typedef,它是一种不接受任何参数并且不返回任何参数的函数,例如:

GLvoid myGLCallback()
{
    return; // do nothing
}