Skip to content

Instantly share code, notes, and snippets.

@bsodhi
Created July 27, 2020 06:44
Show Gist options
  • Save bsodhi/7e447a8a2ef2c650eb61ebd230ddd15c to your computer and use it in GitHub Desktop.
Save bsodhi/7e447a8a2ef2c650eb61ebd230ddd15c to your computer and use it in GitHub Desktop.
Dynamic function invocation in C using table lookup
/**
* When the function to be invoked is determined via a table lookup,
* following is one of the ways to invoke a dyamically loaded function in C.
* Help taken from: https://stackoverflow.com/a/1120834
*/
#include <stdio.h>
#include <string.h>
/**
* These should come from the header file of the respective service
* provider's implementation of the transformation and transport.
*/
void tranform_bmd_PO_svc(void* ptr) { printf("Transformation for PO service: %d\n", *((int*)ptr)); }
void transport_bmd_PO_svc(void* ptr) { printf("Transport for PO service\n"); }
void tranform_bmd_Credit_svc(void* ptr) { printf("Transformation for Credit service: %d\n", *((int*)ptr)); }
void transport_bmd_Credit_svc(void* ptr) { printf("Transport for Credit service\n"); }
/* The ESB would have this table */
const static struct
{
const char *name;
void (*func)(void*);
} function_map[] = {
{"PO svc tranform", tranform_bmd_PO_svc},
{"PO svc transport", transport_bmd_PO_svc},
{"Credit service tranform", tranform_bmd_Credit_svc},
{"Credit service transport", transport_bmd_Credit_svc}
};
/* This is how the ESB may dynamically invoke the service adapter functions */
int call_function(const char *name, void* data)
{
for (int i = 0; i < (sizeof(function_map) / sizeof(function_map[0])); i++)
{
if (!strcmp(function_map[i].name, name) && function_map[i].func)
{
function_map[i].func(data);
return 0;
}
}
return -1;
}
int main()
{
int d = 998;
call_function("PO svc tranform", &d);
call_function("PO svc transport", &d);
call_function("Credit service tranform", &d);
}
@bsodhi
Copy link
Author

bsodhi commented Sep 3, 2021

Another way to invoke a function from a DLL: https://tldp.org/HOWTO/Program-Library-HOWTO/dl-libraries.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment