3

我已经导出了带有相当多样板的函数,并且正在尝试使用字符串混合来帮助隐藏混乱并对其进行修饰。问题是我不知道如何将匿名函数传递给字符串 mixin。如果可能的话,我想避免将函数写成字符串。

// The function that the anonymous function below ultimately gets passed to.
char* magic(F...)(string function(F) func) { ... }

string genDcode(string name, alias func)() {
    return xformat(q{
        extern(C) export char* %s(int blah) {
            // What would I inject into the string in place of 'func'
            // in order to call the 'func' passed into the template?
            return magic(func);
        }
    }, name);
}

// Calls a function to generate code to mix into the global scope.
// The anonymous function must allow abritrary parameters.
mixin(genDcode!("funcName", function(string foo, float bar) {
    return "Herpderp";
}));

这当然不是全貌,大部分样板都被修剪了,但足以说明问题。我曾考虑将函数指针注入为 int,然后转换回可调用类型,但不出所料,您只能在运行时获取函数指针。

我尝试过 mixin 模板,它限制了函数传递问题,但链接器似乎无法找到从此类 mixin 生成的导出函数。它们似乎有一些额外的限定符,我不能在 DEF 文件中使用点。

4

1 回答 1

1

老问题,但一个相对较新的特性可能有助于解决它: D 现在有一个 pragma(mangle) ,您可以将其放在 mixin 模板中以强制链接器使用特定名称:

mixin template genDcode(string name, alias func) {
          // pragma mangle is seen by the linker instead of the name...
        pragma(mangle, name) extern(C) export char* impl(int blah) {
            return magic(func);
        }
}

char* magic(F...)(string function(F) func) { return null; }

mixin genDcode!("funcName", function(string foo, float bar) {
     return "Herpderp";
});
于 2013-11-04T22:27:15.643 回答