I have to write code in C where the user has to have flexibility in choosing any existing DB, write to files, or implement their own storage mechanism. I need wrapper functions that redirect to the right functions corresponding to the storage mechanism selected at runtime or compile time. Say my storage options are FLATFILE and SQLDB and my wrapper function is insert(value). So, if I select FLATFILE as my storage, when I call the wrapper function insert(value), it should in turn call the function that writes to a file. If I choose a SQLDB, insert(value) should call the function that insert the values in the data base.
I know I can somehow use a structure of function pointers to do wrapper functions, but I have no idea how.
Does anyone know of any docs, links, examples, etc I could refer to, to understand and implement something like this? Any pointers will be appreciated. Thanks!
Thanks!
You can use a simple version such as:
All of the above can be hidden inside a C file, with
get_backendand the enumeration being public. Then you can use it like this:Many details are missing, of course (many people like using
typedef, for example). This is a basic setup, you can also create wrapper functions if you don’t like theb->insert(...)syntax or if you want to set the back end once and then useinsert()andremove()in the code. This is also useful if you already have some code that callsinsert()directly and you want to direct the call to the right back end.If you want a more elaborate solution, have a look at http://www.cs.rit.edu/~ats/books/ooc.pdf. You don’t have to implement every last detail from it, but it can give you a few ideas.