<div dir="ltr">A quick sample code to make a table of function pointers at compiler time.<div><br></div><div>module test;</div><div><div>import std.typetuple;</div><div><br></div><div>// calculate compile-time tuple of functions declared in 'mod' module</div>
<div>template getFunctions(alias mod)</div><div>{</div><div> template filterPred(string name)<br></div><div> {</div><div> // if the 'name' is really a function, returns true</div><div> enum filterPred = is(typeof(__traits(getMember, mod, name)) == function);<br>
</div><div> }</div><div> alias names = Filter!(filterPred, __traits(allMembers, mod));</div><div><br></div><div> template mapPred(string name)</div><div> {</div><div> alias mapPred = TypeTuple!(__traits(getMember, mod, name))[0];</div>
<div> }</div><div> alias getFunctions = staticMap!(mapPred, names);</div><div>}</div><div><br></div><div>// gather functions from modname, then make function pointer table</div><div>auto makeTable(alias modname)()</div>
<div>{</div><div> mixin("import "~modname~";");</div><div> mixin("alias funcs = getFunctions!("~modname~");");</div><div><br></div><div> immutable(void*)[] make(size_t n)()</div>
<div> {</div><div> static if (n < funcs.length)</div><div> return cast(immutable(void*))&(funcs[n]) ~ make!(n+1)();</div><div> else</div><div> return [];</div><div> }</div>
<div> immutable(void*)[funcs.length] tbl = make!0()[0 .. funcs.length];</div><div> return tbl;</div><div>}</div><div><br></div><div>// make function pointer table</div><div>immutable func_table = makeTable!"decl"();</div>
<div><br></div><div>void main()</div><div>{</div><div> (cast(void function())func_table[0])();</div><div> assert((cast(int function(int))func_table[1])(10) == 20);</div><div>}</div></div><div><br></div><div>module decl;</div>
<div><div>void fn() { import std.stdio; writeln("call fn"); }</div><div>int bar(int n) { import std.stdio; writeln("call bar"); return n * 2; }</div></div><div><br></div><div>----</div><div><br></div><div class="gmail_extra">
<div class="gmail_extra">$ dmd decl.d -run test</div><div class="gmail_extra">call fn<br></div><div class="gmail_extra">call bar</div><div class="gmail_extra"><br></div><div class="gmail_extra">There's no runtime cost to make function pointer table.</div>
<div class="gmail_extra"><br></div><div class="gmail_extra">Kenji Hara</div><div class="gmail_extra"><br></div><br><div class="gmail_quote">2013/10/20 aldanor <span dir="ltr"><<a href="mailto:i.s.smirnov@gmail.com" target="_blank">i.s.smirnov@gmail.com</a>></span><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">
Yes, in my case it's very specific, let's say I receive a string "fun" and want to call do_fun(args) or Obj.do_fun(args). Thanks, I'll try looking into compile-time reflection.<br>
</blockquote></div><br></div></div>