반응형
    
    
    
  
dlsym(3)
#include <dlfcn.h>
void *dlsym(void *handle, const char *symbol);
이 함수는 dlopen(3)으로 loading한 shared object에서 함수 또는 변수의 pointer를 얻는 함수입니다. return되는 type이 void* 이므로, return된 symbol의 type에 맞는 변수에 type casting을 해야 합니다.
만약, symbol이 함수이면 함수 pointer 변수를 선언해야 하며, 변수이면 변수에 맞는 type을 선언합니다.
링크시 -ldl 추가 필요
파라미터
handle
    - dlopen(3)으로 return 받은 shared object handle
symbol
    - shared object에서 찾고하자 하는 함수명 또는 변수명 등
RETURN
NULL
    - symbol 정보를 찾지 못하였거나 원래 Symbol의 pointer NULL입니다.
    - dlerror(3)를 호출시에 NULL이 return되었다면 정상이라는 의미입니다.(즉, NULL값이 맞다는 의미) 
    - symbol이 만약 함수를 찾는 것이었다면 오류입니다.
NULL 아님
    - symbol (함수명, 변수명 등)이 위치하는 메모리 번지
함수포인터 변수 선언하는 방법 - char *util_strcat(char *dest, const char *src);를 함수 포인터로
함수 Pointer 변수명을 ptr_strcat이라고 정하였다면
1. 사용할 함수의 prototype에서 함수명만 함수 Pointer 변수명으로 변경합니다.
    char *util_strcat(char *dest, const char *src);
    ->
    char *ptr_strcat(char *dest, const char *src);
2. 함수명을 괄호로 묶은 후에 함수명 앞에 *를 붙여줍니다. 
    char *(*ptr_strcat)(char *dest, const char *src); 
3. 파라미터의 가변수 명을 없앱니다.
    char *(*ptr_strcat)(char *, const char *); 
4. NULL로 초기화까지 하려면 = NULL 해주면 됩니다.
    char *(*ptr_strcat)(char *, const char *) = NULL; 
활용 예제
Sample
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv)
{
    void *handle;
    double (*cosine)(double);
    char *error;
    handle = dlopen("libm.so", RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "%s\n", dlerror());
        exit(EXIT_FAILURE);
    }
    dlerror();    /* Clear any existing error */
    /* Writing: cosine = (double (*)(double)) dlsym(handle, "cos");
       would seem more natural, but the C99 standard leaves
       casting from "void *" to a function pointer undefined.
       The assignment used below is the POSIX.1-2003 (Technical
       Corrigendum 1) workaround; see the Rationale for the
       POSIX specification of dlsym(). */
    *(void **) (&cosine) = dlsym(handle, "cos");
    if ((error = dlerror()) != NULL)  {
        fprintf(stderr, "%s\n", error);
        exit(EXIT_FAILURE);
    }
    printf("%f\n", (*cosine)(2.0));
    dlclose(handle);
    
    return 0; 
}
see also: Shared Library 관련 API
반응형
    
    
    
  'C언어 header > dlfcn.h' 카테고리의 다른 글
| dlerror(3) - dynamic library관련 오류 내용 확인 (0) | 2019.10.01 | 
|---|---|
| dlclose(3) - dynamic library unload (0) | 2019.10.01 | 
| dlopen(3) - dynamic library open (0) | 2019.10.01 |