Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

late binding in C

How can late 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!

like image 934
Vijay Avatar asked Jun 18 '10 14:06

Vijay


2 Answers

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;
}
like image 180
Frerich Raabe Avatar answered Sep 21 '22 23:09

Frerich Raabe


@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.

like image 20
Laurențiu Dascălu Avatar answered Sep 22 '22 23:09

Laurențiu Dascălu