在Dlang中传递函数指针

问题描述 投票:6回答:2

我正在尝试使用Dlang运行OpenGL示例。

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

用法:

glfwSetErrorCallback(&onError);

绑定代码:

__gshared {

    da_glfwSetErrorCallback glfwSetErrorCallback;

    ...

extern( C ) @    nogc nothrow {

    alias da_glfwSetErrorCallback = GLFWerrorfun function( GLFWerrorfun );

    ...

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

我得到以下编译器错误:

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)

编译:2.065.0

function d
2个回答
8
投票

来自interfacing to C guidelines的回调:

D可以轻松调用C回调(函数指针),如果回调是extern(C)函数,或者双方同意的其他链接(例如extern(Windows)),C可以调用D代码提供的回调。

所以我认为你需要将你的onError函数声明为extern(C)才能匹配类型签名。


0
投票

您需要在D代码中声明一个函数原型:

// Function prototypes
extern (C) void onError(int, const(char)*) nothrow

extern (C) void onError(int code, const(char)* text) nothrow
{
   //your code
}

请注意,在原型中只有类型。

© www.soinside.com 2019 - 2024. All rights reserved.