为什么这个函数被视为委托?

Why is this function seen as a delegate?

在尝试包装接受回调的 C 函数时,我遇到了成员函数被视为委托的问题。 C 函数不接受委托,所以我决定采用其他方法:

extern(C) void onMouse(void delegate(int, int, int) nothrow callback)
{
    glfwSetMouseButtonCallback(handle,
        function void (GLFWwindow* h, int button, int action, int mods) nothrow
        {
            callback(button, action, mods);
        }
    );
}

如您所见,我向回调设置函数传递了一个调用委托的函数文字(这将是我在此处传递的成员函数)。

然而,它并没有像我预期的那样结束:

Error: function pointer glfwSetMouseButtonCallback (GLFWwindow*, extern (C) void function(GLFWwindow*, int, int, int) nothrow) is not callable using argument types (GLFWwindow*, void delegate(GLFWwindow* h, int button, int action, int mods) nothrow @system)

在错误中,它显示第二个参数的类型为void delegate

所以。我的问题是:为什么会发生这种情况? 如您所见,代码中显示 function void

注意:我看过这个:Pass delegates to external C functions in D。 该解决方案显然是一个黑客。但如果我在互联网上找不到解决方法,我会尝试一下。

即使您将其声明为函数,它也不能。它依赖于您传递给 onMouse 的参数。该参数是一个局部变量,在函数体中访问它们会使它们成为委托。您所能做的就是将参数更改为 function 并使用 &callback 传递它(然后您需要添加 GLFWwindow 作为参数)。

或者,您可以创建一个全局列表,此回调将事件放入其中,然后您可以在主循环中处理这些事件。