gpt4 book ai didi

d - 从字符串混合中调用函数引用

转载 作者:行者123 更新时间:2023-12-04 09:25:47 26 4
gpt4 key购买 nike

我已经导出了带有大量样板的函数,并且正在尝试使用字符串混合来帮助隐藏困惑并将其加糖。问题是我不知道如何将匿名函数传递给字符串混合。如果可能的话,我想避免将函数写成字符串。

// 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 注入(inject),然后转换回可调用类型,但不出所料,您只能在运行时获取函数指针。

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

最佳答案

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

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

关于d - 从字符串混合中调用函数引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13150220/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com