2012-10-31 16 views
3

我已经导出了很多样板文件的函数,并试图使用字符串mixin来帮助隐藏混乱并将其加糖。问题是我不知道如何将一个匿名函数传递给字符串mixin。如果可能的话,我想避免把函数写成字符串。从一个字符串调用函数引用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模板,它可以消除传递函数的问题,但链接器似乎无法找到从这样的mixins生成的导出函数。他们似乎有一些额外的限定符,我不能在DEF文件中使用点。

+0

如果' func'是一个命名和可访问的符号,比如一个常规的命名函数,你可以使用'__traits(identifier,func)'来得到一个可混合的字符串引用,但这不适用于匿名符号。 Mixin模板在这里不起作用,因为mixin模板中的函数名称无论其链接如何都会被破坏。我希望这是固定的,因为mixin模板更清洁,并且感觉不那么黑。无论如何,如果将以下pull请求合并,mixin模板方法在将来可能更加可行:https://github.com/D-Programming-Language/dmd/pull/1085 –

+0

谢谢,我会密切关注那拉请求。我想在使用模板时必须小心避免重复的“损坏”名称,但这对我来说不应该是个问题,因为名称是模板参数之一。 – YotaXP

回答

1

老问题,而是一个相对较新的功能,可以帮助解决这个问题:现在D具有编译(轧液),你可以把一个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"; 
}); 
相关问题