www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Using arrays of function pointers in D

reply "John" <typ3def gmail.com> writes:
I've been rewriting one of my emulators in D and am fairly new to 
the language. I'm having trouble finding documentation on 
creating/initializing/use of arrays of function pointers in D. If 
anyone has a code example I'd appreciate it!
May 21 2015
next sibling parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
Start with a function type declaration:

void function() func_ptr;

Then make an array out of it:

void function()[] func_ptr_array;


It works like other arrays, just the [] might be a little harder 
to see since it is a much longer type signature. But it is still 
in there, right after it, similarly to int[].

Then the array is indexed and set like normal. You can change 
length on it (auto initializes all members to null), ~= &my_func 
to append, etc.

You can also do associative arrays of function pointers btw.
May 21 2015
parent "John" <typ3def gmail.com> writes:
On Thursday, 21 May 2015 at 16:25:24 UTC, Adam D. Ruppe wrote:
 Start with a function type declaration:

 void function() func_ptr;

 Then make an array out of it:

 void function()[] func_ptr_array;


 It works like other arrays, just the [] might be a little 
 harder to see since it is a much longer type signature. But it 
 is still in there, right after it, similarly to int[].

 Then the array is indexed and set like normal. You can change 
 length on it (auto initializes all members to null), ~= 
 &my_func to append, etc.

 You can also do associative arrays of function pointers btw.
Thanks! Holy moly you guys are quick in here.
May 21 2015
prev sibling parent "John Colvin" <john.loughran.colvin gmail.com> writes:
On Thursday, 21 May 2015 at 16:23:15 UTC, John wrote:
 I've been rewriting one of my emulators in D and am fairly new 
 to the language. I'm having trouble finding documentation on 
 creating/initializing/use of arrays of function pointers in D. 
 If anyone has a code example I'd appreciate it!
float foo(int a, float b) { import std.stdio; writeln(a, b); return a+b; } void main() { float function(int, float)[] arrayOfFPs; arrayOfFPs = new float function(int, float)[42]; arrayOfFPs[0] = &foo; auto r = arrayOfFPs[0](3, 7.6); assert(r == 3+7.6f); alias DT = int delegate(int); int a = 4; auto arrayOfDelegates = new DT[3]; arrayOfDelegates[1] = (int x) => a + x; assert(arrayOfDelegates[1](3) == 7); }
May 21 2015