Search code examples
cdelegatesargumentsdfunction-literal

Why is this function seen as a delegate?


In an attempt to wrap a C function taking callbacks, I encountered the problem of member functions being seen as delegates. The C function wouldn't take delegates, so I settled on something else instead:

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

As you can see, I'm passing to the callback setting function a function literal calling a delegate (which would be the member function I pass here).

However, it doesn't end up as I expect:

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)

In the error, it shows the second parameter as being as the type void delegate.

So. My question is: why does this happen? As you can clearly see, it says function void in the code.

NOTE: I've seen this: Pass delegates to external C functions in D. The solution is apparently a hack. But I will try it if I cannot find a workaround on the internet.


Solution

  • Even though you declare it as function, it cannot be. It relies on the parameter you pass to onMouse. That parameter is a local variable, and accessing them in a function body makes them a delegate. All you can do is change the parameter to function and pass it with &callback (you'd need to add GLFWwindow as parameter then).

    Alternatively, you can create a global list in which this callback puts events which you can then process in your main loop.