I have exported functions with quite a bit of boilerplate, and am attempting to use string mixins to help hide the mess and sugar it up. The problem is that I have no idea how I could pass an anonymous function into the string mixin. I'd like to avoid writing the function as a string if at all possible.
// 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";
}));
This is of course not the full picture, and most of the boilerplate is trimmed, but it's enough to show the problem. I've thought about injecting the function pointer as an int, and casting back into a callable type, but unsurprisingly, you can only get the function pointer at runtime.
I've tried mixin templates, which elimitates the function passing problem, but the linker cannot seem to find export functions generated from such mixins. They appear to have some extra qualifiers, and I can't use a dot in the DEF file.
Old question, but a relatively new feature might help solve it: D now has a pragma(mangle) which you can put inside a mixin template to force a particular name for the linker:
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";
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With