Search code examples
cinterfaceimplementation

How to use different implementaions of an interface in C?


I want to implement a differentiable function in C. Essentially, it is a struct that has two funcion pointers. One to calculate a function value, another to calculate its differential. The struct is declared inside of a header file. Ideally, my application should only know about this interface: the object is a struct with two function pointers, those functions convert a double to another double.

The problem is that I don't know how to properly provide an implementation (or multiple implementations) of this interface to my program. I have five differentiable functions and I need to switch between them in runtime. I also can decide to use more or less of them in future. In Java I would just import the interface and its implementations (may be the entire package), it would ensure type safety and unused imports would not impact performance. But in C I can't just include whatever I want because it gets literally copied into the program. I also don't want to change compilation commands inside of my Makefile since it is not explicitly reflected in my code.

Memory usage and performance aren't that important as readability and modularity. I do not insist on that my approach is fundamentally right and I'm willing to switch it. Is there a conventional way of solving such a task in C?


Solution

  • Essentially, it is a struct that has two funcion pointers. One to calculate a function value, another to calculate its differential.

    struct Function { double (*f)(double), (*df)(double); };
    

    The problem is that I don't know how to properly provide an implementation (or multiple implementations) of this interface to my program.

    struct Function Sine = { sin, cos };
    

    Demonstration:

    struct Function { double (*f)(double), (*df)(double); };
    
    
    #include <math.h>
    #include <stdio.h>
    
    
    struct Function Sine = { sin, cos };
    
    
    static void Demonstrate(struct Function F, double x)
    {
        printf("f(%g) = %g.\n", x, F.f(x));
        printf("df(%g) = %g.\n", x, F.df(x));
    }
    
    
    int main(void)
    {
        Demonstrate(Sine, 3.1415926535897932384626433/6);
    }