Call function by its string name

Artur Skawina art.08.09 at gmail.com
Sat Oct 19 12:21:18 PDT 2013


On 10/19/13 18:33, aldanor wrote:
> I was wondering if it was possible to call D functions by their names (strings that are not known at compile time) and couldn't find the answer anywhere in the documentation. Kinda like we can instantiate objects with Object.factory, would it be possible to somehow do the same with module-level functions? Or maybe with non-static class methods?

You can build a name->funcPtr table at CT and look up at RT.

You could also let the dynamic linker handle it, but that approach will be
less portable. For example, this will work in linux:

==========================================================================
   // gdc dlopen1.d -o dlopen1 -ldl -Wl,--export-dynamic && ./dlopen1 f1 2
   import std.stdio;
   
   alias int function(int) FT;
   int dummy42(int a);
   int f1(int a) { int i = 42+a; writeln(i); return i; }
   int f2(int a) { int i = 17*a; writeln(i); return i; }
   
   int main(string[] argv) {
      import std.conv, std.array;
      auto mnamehack = replace(dummy42.mangleof, "7dummy42", 
                                  to!string(argv[1].length)~argv[1])~"\0";
      auto fp = cast(FT)dlsym(RTLD_DEFAULT, mnamehack.ptr);
      if (!fp)
         { writeln(to!string(dlerror())); return 1; }
      return fp(to!int(argv[2]));
   }

   extern (C) void* dlsym(const void* handle, const char* symbol);
   extern (C) const(char)* dlerror();
   enum RTLD_DEFAULT = null;
==========================================================================

Of course this is just an example - the name mangling is hack (maybe there
is something in druntime/phobos that could help), but enough for many cases
where you just want to choose from a known set of functions/methods at RT.

artur 


More information about the Digitalmars-d mailing list