简体   繁体   English

如何传递extern(C)函数文字?

[英]How can I pass an extern(C) function literal?

Say I am interfacing to C. 说我正在接口C.

Here is an wrapping function to the interface. 这是接口的包装功能。

@property extern(C) void onEvent(void function(InterfaceStruct*, int, int, int) nothrow callback)
{
        interfaceSetCallback(handle, callback);
}

All good. 都好。

wrapper.onEvent = function void  (InterfaceStruct*, int x, int y, int z) nothrow
{
        if (x == 11) doSomething();
};

Uh oh: 哦哦:

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)

So, it wants me to have the function literal being extern(C). 所以,它希望我的函数文字是extern(C)。 So how can I do that? 那我该怎么办呢? I can't find any way to do so. 我找不到任何办法这样做。

Instead of providing the whole function definition you can simply assign onEvent using 您可以简单地使用onEvent分配,而不是提供整个函数定义

wrapper.onEvent = (a, x, y, z)
{
    if (x == 11) doSomething();
};

D will automatically assign it the correct type. D将自动为其指定正确的类型。

Also your code should actually give you a syntax error because extern(C) is actually not allowed when using it for a function pointer definition. 此外,您的代码实际上应该给您一个语法错误,因为当将它用于函数指针定义时实际上不允许使用extern(C)。

You could alternatively define an alias for the function pointer type and cast the assignment to it like this: 您也可以为函数指针类型定义别名,并将赋值转换为它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM