2

I am attempting to get the function pointer by using dlopen and dlsym, however I have been unable to get it working correctly. It fails when trying to doing the dlsym call. Following is my code.

Any help please?

#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>

int test() {
    printf("%s", "test()");
    return 123;
}

int main() {
    char * functionname = "test";
    void* handle = dlopen(NULL,RTLD_LAZY|RTLD_GLOBAL);
    if (!handle) {
        fprintf(stderr, "Couldn't open handle: %s\n",
            dlerror());
        exit(1);
    }

    int (*fun)() = (int (*)())dlsym(handle, functionname);
    if (fun == NULL) { 
        fprintf(stderr, "Couldn't find function: %s\n",functionname); 
        exit(1);
    }
    int a = fun();
    printf("result: %d \n", a);
}
9
  • What makes you certain the symbol test exists in the library? Commented Mar 21, 2014 at 14:13
  • should it not be exist as I defined it in the main? From dlopen "If filename is a NULL pointer, then the returned handle is for the main program." Commented Mar 21, 2014 at 14:16
  • I see, I misunderstood the question; I didn't notice you were looking to get the symbol from your own executable. I'm not positive it's done the way you're trying to though... what happens if you search for the symbol via dlsym(NULL, function name);? Commented Mar 21, 2014 at 14:18
  • same thing happens if I call dlsym(NULL,..) though it does not really make sense to that that either. dlsym expects the handle obtained by the dlopen call. Commented Mar 21, 2014 at 14:22
  • 1
    You may need to apply some linker options when you build. See stackoverflow.com/questions/6292473/… for possibilities to try. Commented Mar 21, 2014 at 14:55

1 Answer 1

7

Probably you need to specify to the linker to export the symbols as dynamic. With gcc you have to use -rdynamic.

You can check the exported dynamic symbols with objdump -T.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.