Reputation: 2907
Recently, I've been seeing an interesting way to implement an analogue of explicit namespacing in C. This is accomplished by using a struct
to store const
function pointers, like this:
foo.h:
extern const struct foo_namespace {
void (* const bar)(int a, int b);
int (* const baz)();
char *(* const qux)(const char *str);
} Foo;
foo.c:
#include "foo.h"
const struct foo_namespace Foo = {
.bar = /* some function */,
.baz = ... ,
.qux = ...
};
This allows one to call the functions as Foo.bar()
, similar to C++'s Foo::bar()
. I've been thinking about this technique and would like to use it, but thought of some issues.
Is the compiler likely to inline the entire struct such that calls through the function pointers are replaced by the functions themselves? It seems unlikely since const
does not actually declare a compile-time constant. This would also make it impossible to have any namespaced functions inlined.
What executable section is this likely to be stored in? It seems possible that this could be a security problem if it's possible to clobber the struct and install different function pointers.
Upvotes: 2
Views: 206
Reputation: 4855
1) you don't care, with branch prediction the overhead is in the nanoseconds.
2) consts are usually copied to ram for faster access. But the risk seems the same as using symbols to resolve functions.
Upvotes: 1