user16367
user16367

Reputation: 273

Access pointer from shared library in C

I built a shared library which exposes an array of function pointers. The function definitions are also in this library, but they are not exported.

Is it possible, from another program, to load this library and call those functions using the exported pointers directly?

This is what I'm trying to do.

My library:

#include <stdio.h>
void myfun(){
    printf("myfun\n");
}
extern void (*myptr)() = myfun;

I'm trying to use it like this:

#include <dlfcn.h>
int main(){
    void * lib = dlopen("libt1.so", RTLD_NOW);
    if(!lib) { printf("%s\n", dlerror()); return 0; }
    void (*myptr)() = (void (*)()) dlsym(lib, "myptr");
    if(!myptr){ printf("%s\n", dlerror()); return 0; }
    printf("%p\n", myptr);
    myptr();
}

This gives a segm fault.

Upvotes: 3

Views: 832

Answers (2)

user16367
user16367

Reputation: 273

It was a silly mistake it seems.

void (*myptr)() = (void (*)()) dlsym(lib, "myptr");

Should be something like this:

void ** myptr = (void**)dlsym(lib, "myptr");
void (*fcn)() = (void (*)()) (*myptr);

It is working as expected now.

Upvotes: 1

James M
James M

Reputation: 16718

Yes, of course. dlsym looks up a function name in the symbol table to convert it to an address (function pointer), so by building your own table of function pointers you're pretty much just doing this manually.

Upvotes: 0

Related Questions