I am about to use dlopen() to open shared object. Do I need to include corresponding headers if shared object?

StackOverflow https://stackoverflow.com/questions/20321802

  •  07-08-2022
  •  | 
  •  

質問

I have to use dlopen() and access functions from shared object in my code. Do I need to include headers of corresponding functions of shared object ?

役に立ちましたか?

解決

Because of the way dlopen() and dlsym() operate, I don't see how that would accomplish anything. Very roughly speaking, dlopen() copies the library binary into your program space and adds the addresses of its exported symbols (i.e. global functions & variables) to your program's symbol table.

Because the library was not linked to your program at compile-time, there's no way your code could possibly know the instruction addresses of these new functions tacked on at run-time. The only way to access a run-time dynamically linked symbol is via a pointer obtained from dlsym().

You have to create a function pointer for each and every library definition that you want to use. If you want to call them like regular functions, in C-language you can manually typedef type definitions for the function pointers, specifying their parameters and return values, then you can call the pointers just like regular functions. But note that you have to define all of these manually. Including the library header doesn't help.

In C++ I think there are issues with storing dlsym() output in a typedef'd pointer due to stricter standards, but this should work in C:

addlib.c (libaddlib.dylib):

int add(int x, int y) {
    return x+y;
}

myprogram.c:

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

typedef int (*add_t)(int, int);

int main() {
    void *lib_handle;
    add_t add;  // call this anything you want...it's a pointer, it doesn't care

    lib_handle = dlopen("libaddlib.dylib", RTLD_NOW);
    if (lib_handle == NULL) {
        // error handling
    }

    add = (add_t)dlsym(lib_handle, "add");
    if (add == NULL) {
        // error handling
    }

    printf("Sum is %d\n", add(17, 23));

    dlclose(lib_handle);    // remove library from address space
    return 0;
}

(Update: I compiled the dylib and myprogram...it works as expected.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top