c - 将委托(delegate)传递给 D 中的外部 C 函数

标签 c delegates function-pointers d

如何在 D 中将委托(delegate)传递给采用函数指针的外部 C 函数?

最佳答案

让我交叉张贴我在新闻组上所说的话:

How do I pass a delegate to an external C function taking a function pointer?

一般不能直接做,除非能修改C 功能,那么你可以绕过它,但是一个委托(delegate)和一个 常规函数指针是完全不同的动物。

但也许你可以用魔法破解它。观察:

// a C function that needs a plain function
extern(C) void test(void function() f) {
    // pretend this is implemented in C
    f();
}

// just create a random delegate
void delegate() foo(int a) {
    return { import std.stdio; writeln(a); };
}

// what we want to work
void main() {
    auto dg = foo(10);
    dg(); // works

    //test(dg); // won't work
    test(bindDelegate(dg)); // we want this
}

// transform delegate into pointer..
import std.traits;
auto bindDelegate(T, string file = __FILE__, size_t line = __LINE__)(T t) if(isDelegate!T) {
    static T dg;

    dg = t;

    extern(C)
    static ReturnType!T func(ParameterTypeTuple!T args) {
            return dg(args);
    }

    return &func;
}

bindDelegate 所做的是创建一个特殊的静态变量并且 该特定调用的功能。就好像我们单独写了一个 函数和全局来保存它。

__FILE__, __LINE__ 东西是一个肮脏的黑客来制作它 为不同的对象实例化一个单独的变量+函数对 行,因此持有委托(delegate)的全局变量不会如此 很容易被覆盖。

关于c - 将委托(delegate)传递给 D 中的外部 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22845175/

相关文章:

c# - 用于优化的线程使用

c++ - 函数指针模板参数个数

c - 随机(时间(NULL))

iOS:处理 App Delegate 中的无效 session

c# - 如何将通过反射获得的方法分配给委托(delegate)? (或 : how to speed up method calls through reflection)

c++ - 将模板函数指针作为模板参数传递给模板过于冗长

c++ - Stackoverflow 和函数指针

在 C 中使用 pow 时,CMake 能否检测到我是否需要链接到 libm?

c++ - 使用 typedef 和 #define 的不同原型(prototype)

c - 输出正确的单词