Emulating namespaces in 'C' using function pointers.

Thread Starter

ApacheKid

Joined Jan 12, 2015
1,762

BobaMosfet

Joined Jul 1, 2009
2,211
I just stumbled upon this suggestion that gives us namespace-like capabilites when working in C. This leverages function pointers in a way I never considered.
This is the most common way in which you use function-pointers to abstract access to things like devices through a single structure called a parameter block. This is used heavily in O/S queuing, window and control managers, and more.

Don't think about it in terms of namespaces- if you do, you limit your understanding of what you can do with this. Remember, C++ originally was nothing more than header files to a C compiler. C++ compilers improved in stages after that point.

Very, very few people ever realize the full power and strength of C- it allows one to do _anything_ codewise without limits. One simply must be experienced enough and clever enough to understand how to harness that power wisely.
 

Thread Starter

ApacheKid

Joined Jan 12, 2015
1,762
Oh I do understand that, the point of the post was to show how you can setup a namespace like mechanism when using C.

The problem I was seeking to solve was to be able to lump functions together into named "libraries".

Then we could code stuff like:

Peripherals.ADC.Initialize(...)

or

System.Reboot(...)

and so on, with ordinary C there is no out-of-the-box way to get this namespace like capability and without it, over time we can end up with huge numbers of oddly named functions.
 

402DF855

Joined Feb 9, 2013
271
Care should be taken IMO to help subsequent programmers (including the author) to know what functions are being pointed to. I first ran across this sort of thing in the JPEGLIB where much of the image format can involve various choices and this method really helps to implement them all. Recently I was using openssl and it uses much the same technique given different options for hashing and encryption, for example.

In both cases really the only way to see what function was being invoked was to set breakpoints if a debugger is available, or worse, printfs to see what is called. The latter is what I needed to use in order to find the exact subroutines that were being used to perform the decryption of validating a signature in a certificate. The quickest way to find the right routine was to grep for candidates, put printfs in the code, recompile openssl and track it that way.

Along with power comes great responsibility.
 
Top