How to correctly assign a pointer returned by dlsym into a variable of function pointer type?

前端 未结 6 1086
悲&欢浪女
悲&欢浪女 2020-12-31 01:00

I am trying to use dlopen() and dlsym() in my code and compile it with gcc.

Here is the first file.

/* main.c          


        
6条回答
  •  孤城傲影
    2020-12-31 01:30

    If you want to be pedantically correct, don't try to resolve the address of a function. Instead, export some kind of structure from the dynamic library:

    In the library

    struct export_vtable {
       void (*helloworld)(void);
    };
    struct export_vtable exports = { func };
    

    In the caller

    struct export_vtable {
       void (*helloworld)(void);
    };
    
    int main() {
       struct export_vtable* imports;
       void *handle = dlopen("./foo.so", RTLD_NOW);
    
       if (handle) {
            imports = dlsym(handle, "exports");
            if (imports) imports->helloworld();
        }
    
        return 0;
    }
    

    This technique is actually quite common, not for portability -- POSIX guarantees that function pointers can be converted to and from void* -- but because it allows more flexibility.

提交回复
热议问题