如何传递 extern(C) 函数文字?
How can I pass an extern(C) function literal?
假设我正在连接到 C。
这是接口的包装函数。
@property extern(C) void onEvent(void function(InterfaceStruct*, int, int, int) nothrow callback)
{
interfaceSetCallback(handle, callback);
}
一切顺利。
wrapper.onEvent = function void (InterfaceStruct*, int x, int y, int z) nothrow
{
if (x == 11) doSomething();
};
呃哦:
Error: function foo.bar.onEvent (void function(InterfaceStruct*, int, int, int) nothrow callback) is not callable using argument types (void function(InterfaceStruct* _param_0, int x, int y, int z) nothrow @nogc @safe)
因此,它希望我将函数文字设为 extern(C)。那我该怎么做呢?我找不到任何方法。
无需提供整个函数定义,您只需使用
分配 onEvent
wrapper.onEvent = (a, x, y, z)
{
if (x == 11) doSomething();
};
D 会自动为其分配正确的类型。
此外,您的代码实际上应该给您一个语法错误,因为在将其用于函数指针定义时实际上不允许使用 extern(C)。
您也可以为函数指针类型定义一个别名,然后像这样对其赋值:
alias EventCallback = extern(C) void function(InterfaceStruct*, int, int, int) nothrow;
@property extern(C) void onEvent(EventCallback callback)
{
interfaceSetCallback(handle, callback);
}
// ...
wrapper.onEvent = cast(EventCallback) function void(InterfaceStruct*, int x, int y, int z) nothrow
{
if (x == 11) doSomething();
};
假设我正在连接到 C。
这是接口的包装函数。
@property extern(C) void onEvent(void function(InterfaceStruct*, int, int, int) nothrow callback)
{
interfaceSetCallback(handle, callback);
}
一切顺利。
wrapper.onEvent = function void (InterfaceStruct*, int x, int y, int z) nothrow
{
if (x == 11) doSomething();
};
呃哦:
Error: function foo.bar.onEvent (void function(InterfaceStruct*, int, int, int) nothrow callback) is not callable using argument types (void function(InterfaceStruct* _param_0, int x, int y, int z) nothrow @nogc @safe)
因此,它希望我将函数文字设为 extern(C)。那我该怎么做呢?我找不到任何方法。
无需提供整个函数定义,您只需使用
分配 onEventwrapper.onEvent = (a, x, y, z)
{
if (x == 11) doSomething();
};
D 会自动为其分配正确的类型。
此外,您的代码实际上应该给您一个语法错误,因为在将其用于函数指针定义时实际上不允许使用 extern(C)。
您也可以为函数指针类型定义一个别名,然后像这样对其赋值:
alias EventCallback = extern(C) void function(InterfaceStruct*, int, int, int) nothrow;
@property extern(C) void onEvent(EventCallback callback)
{
interfaceSetCallback(handle, callback);
}
// ...
wrapper.onEvent = cast(EventCallback) function void(InterfaceStruct*, int x, int y, int z) nothrow
{
if (x == 11) doSomething();
};