Access pointer from shared library in C

I have built a shared library that provides an array of function pointers. Function definitions are also in this library, but they are not exported.

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

This is what I am trying to do.

My library:

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

      

I am 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 results in a segm error.

+3


source to share


2 answers


Yes of course. dlsym

looks up the function name in the symbol table to convert it to an address (function pointer), so by creating your own function pointer table you almost just do it manually.



0


source


It was a stupid mistake.

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

      

There should be something like this:



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

      

It now works as expected.

+1


source







All Articles