Search code examples
dmixins

Mixins with variable number of string arguments in D?


I'm working on some D bindings for an existing C library, and I have a bunch of function definitions, and a bunch of bindings for them. For example:

// Functions
void function(int) funcA;
long function() funcB;
bool function(bool) funcC;
char function(string) funcD;
// etc...

// Bindings
if(!presentInLibrary("func")) return false;
if(!bindFunction(funcA, "funcA")) return false;
if(!bindFunction(funcB, "funcB")) return false;
if(!bindFunction(funcC, "funcC")) return false;
if(!bindFunction(funcD, "funcD")) return false;
// etc...

This model is very similar to how Derelict handles OpenGL extension loading. However, this seems like a lot of redundant typing. I'd really like a way to express the "binding" portion above as something like:

BINDGROUP("func", "funcA", "funcB", "funcC", "funcD", ...); // Name of function group, then variable list of function names.

Is this something that can be done with mixins?


Solution

  • I used this when I was doing dynamic loading, while it doesn't answer your question you may be able to adapt it:

    void function() a;
    int function(int) b;
    void function(string) c;
    
    string bindFunctions(string[] funcs...)
    {
        string ret;
        foreach (func; funcs)
        {
            ret ~= func ~ ` = cast(typeof(` ~ func ~ `))lib.getSymbol("` ~ func ~ `");`;
        }
        return ret;
    }
    mixin(bindFunctions("a", "b", "c"));
    

    Here bindFunctions("a", "b", "c") returns a string that looks something like:

    a = cast(typeof(a))lib.getSymbol("a");
    b = cast(typeof(b))lib.getSymbol("b");
    c = cast(typeof(c))lib.getSymbol("c");
    

    Where lib.getSymbol() returns a pointer from dl_open() etc. Hope this helps.