Search code examples
functiond

Passing function pointer in Dlang


I'm trying to run OpenGL sample with Dlang.

void onError(int code, const(char)* text) nothrow
{
}

Usage:

glfwSetErrorCallback(&onError);

Binding code:

__gshared {

    da_glfwSetErrorCallback glfwSetErrorCallback;
    
    ...

extern( C ) @    nogc nothrow {

    alias da_glfwSetErrorCallback = GLFWerrorfun function( GLFWerrorfun );

    ...

    alias GLFWerrorfun = void function( int, const( char )* );

And i get the following compiler error:

Error: function pointer glfwSetErrorCallback (extern (C) void function(int, const(char)*) nothrow) is not callable using argument types (void function(int code, const(char)* text) nothrow)

Compiler: 2.065.0


Solution

  • From the interfacing to C guidelines on callbacks:

    D can easily call C callbacks (function pointers), and C can call callbacks provided by D code if the callback is an extern(C) function, or some other linkage that both sides have agreed to (e.g. extern(Windows)).

    So I think you need your onError function to be declared as extern(C) in order for it to match the type signature.