Thread overview
Using arrays of function pointers in D
May 21, 2015
John
May 21, 2015
Adam D. Ruppe
May 21, 2015
John
May 21, 2015
John Colvin
May 21, 2015
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
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
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
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.