late binding in C
How can late开发者_JAVA技巧 binding can be achieved in c language? can anybody please provide an example.
i think it can be achieved using dlopen and dlsym but i am not sure about it.please correct me if i am wrong!
Late (AKA Dynamic) Binding doesn't have anything to do with dynamically loaded modules (which is what dlopen and dlsym are about) per se. Instead, it is about delaying the decision about which function is called until runtime.
In C, this is done using function pointers (which is also how virtually any C++ implementation does it for virtual functions).
One way to emulate this is to pass structs of function pointers around and then only call functions via the given function pointers.
An example:
typedef struct Animal {
void (*sayHello)(struct Animal *a, const char *name);
} Animal;
static void sayQuakQuak( Animal *a, const char *name ) {
printf( "Quak quak %s, says the duck at 0x%x!\n", name, a );
}
/* This function uses late binding via function pointer. */
void showGreeting( Animal *a, const char *name ) {
a->sayHello( a, name );
}
int main() {
struct Animal duck = {
&sayQuakQuak
};
showGreeting( &duck, "John" );
return 0;
}
@Frerich Raabe: The basic late binding mechanism can be implemented as your said, but you can use a combination of dlopen/dlclose/dlsym and pointers to function to get something like:
void *libraryHandle;
void (*fp)(void);
if (something)
libraryHandle = dlopen("libmylibrary0.1");
else
libraryHandle = dlopen("libmylibrary0.2");
fp = dlsym(libraryHandle, "my_function");
fp();
I think this is what Benjamin Button is looking for.
精彩评论