alexl
alexl

Reputation: 1914

can a dlopened module call a function in the caller?

say I have a parent and a child, the child calls a function "hello" in the child with dlopen. Can the child then call a function "world" in the parent? I keep getting symbol lookup error: ./child.so: undefined symbol: world

here are the files. parent.c

#include <dlfcn.h>
typedef void (*fptr)();
#include <stdio.h>

int main () {
 void*handle=dlopen("./child.so",RTLD_LAZY);
 fptr f=dlsym(handle,"hello");
 f();
 return 0;
}

void world() {
 printf ("world");
}

and child.c

#include <stdio.h>
void hello () {
 printf ("hello");
 world();
}

Upvotes: 2

Views: 417

Answers (3)

alexl
alexl

Reputation: 1914

I found the answer here:

gcc -rdynamic hello.c -ldl

Upvotes: 2

Yes, it a dlopen-ed module can call functions from the calling program, provided that the calling program has been linked with the -rdynamic option.

BTW, most plugins need that feature: a firefox plugin obviously wants to call firefox functions.

Read also about visibility function __attribute__ ... Read also Drepper's How to Write Shared Libraries long paper and dlopen(3) man page.

Upvotes: 2

egur
egur

Reputation: 7970

Surprisingly it can. I've personally seen it happen.

You may need to link to the executable with -rdynamic

Upvotes: 1

Related Questions