www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - C function taking two function pointers that share calculation

reply jmh530 <john.michael.hall gmail.com> writes:
There is a C library I sometimes use that has a function that 
takes two function pointers. However, there are some calculations 
that are shared between the two functions that would get pointed 
to. I am hoping to only need to do these calculations once.

The code below sketches out the general idea of what I've tried 
so far. The function `f` handles both of the calculations that 
would be needed, returning a struct. Functions `gx` and `gy` can 
return the field of the struct that is relevant. Both of them 
could then get fed into the C function as function pointers.

My concern is that `f` would then get called twice, whereas that 
wouldn't be the case in a simpler implementation (`gx_simple`, 
`gy_simple`). ldc will optimize the issue away in this simple 
example, but I worry that might not generally be the case.

How do I ensure that the commonCalculation is only done once?

```d
struct Foo
{
     int x;
     int y;
}

Foo f(int x, int a)
{
     int commonCalculation = a * x;
     return Foo(commonCalculation * x, 2 * commonCalculation);
}

int gx(int x, int a) { return f(x, a).x;}
int gy(int x, int a) { return f(x, a).y;}

//int gx_simple(int x, int a) { return a * x * x;}
//int gy_simple(int x, int a) { return 2 * a * x;}

void main() {
     import core.stdc.stdio: printf;
     printf("the value of x is %i\n", gx(3, 2));
     printf("the value of y is %i\n", gy(3, 2));
}
```
Sep 14 2022
parent reply JG <someone simewhere.com> writes:
On Wednesday, 14 September 2022 at 17:23:47 UTC, jmh530 wrote:
 There is a C library I sometimes use that has a function that 
 takes two function pointers. However, there are some 
 calculations that are shared between the two functions that 
 would get pointed to. I am hoping to only need to do these 
 calculations once.

 [...]
Maybe others know better but I would have thought the only way is to use globals to do this. Often c libraries that I have used get round this by taking a function and a pointer and then the library calls your function on the pointer simulating a d delegate.
Sep 14 2022
parent jmh530 <john.michael.hall gmail.com> writes:
On Wednesday, 14 September 2022 at 18:02:07 UTC, JG wrote:
 [snip]

 Maybe others know better but I would have thought the only way 
 is to use globals to do this. Often c libraries that I have 
 used get round this by taking a function and a pointer and then 
 the library calls your function on the pointer simulating a d 
 delegate.
The C function does make use of a pointer to some data (that I neglected to mention), but your comment gives me an idea. Thanks.
Sep 14 2022