#Dependency injection in C

2 messages · Page 1 of 1 (latest)

pliant falcon
#

Hi all,

I just wanted to know if you ever used some kind of dependency injection in your C projects.

Here some example code to explain in more detail:

#include <stdio.h>

static void some_api_function1(void)
{
  printf("call 1 from API\n");
}

static void some_api_function2(int some_arg)
{
  printf("call 2 from API with arg %d\n", some_arg);
}

static void do_something_v1(void)
{
  printf("call from outside API v1\n");
  some_api_function1();
  some_api_function2(123);
}
typedef void (*f1)(void);
typedef void (*f2)(int);
struct ApiInterface
{
  f1 func1;
  f2 func2;
};

static void do_something_v2(struct ApiInterface *api_interface)
{
  printf("call from outside API v2\n");
  
  // I skipped the check for valid pointer and valid function pointers here
  api_interface->func1();
  api_interface->func2(234);
}

int main(int argc, char **argv)
{
  printf("call from main\n");
  do_something_v1();
  
  ApiInterface api;
  api.func1 = &some_api_function1;
  api.func2 = &some_api_function2;
  do_something_v2(&api);
  return 0;
}

There are 2 ways to call functions: directly(hard coupled) and with dependency injection(loosely coupled).

The idea behind the second option is to easily mock calls to other modules for testing purposes, e.g. a host simulation for devices with hardware usage(I2C, CAN, ...) or for unit testing.

Now my question is if you ever used this mechanism and if yes what was your experience?

dense wingBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.