天天看點

dlopen、dlsym的簡單使用

一、dlopen、dlsym我所了解的是通過dlopen可以動态加載一個so,通過dlsym可以獲得該so中某接口的位址,進而實作使用該so中接口的功能。

二、代碼如下:

mylib.cpp

#include <stdio.h>
#include <stdlib.h>

/*
 *  c++編譯後的檔案會把函數名改名(為了實作重載功能)
 *  用extern "C"聲明後,就會使用c的方式進行編譯,編譯後的檔案中仍然是定義的函數名
 */
extern "C"
{
    void feng(void)
    {
        printf("111111\n");
    }
}
           
g++ -shared -fPIC -o mylib.so mylib.cpp 
           

dlopen_test.cpp

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

void(*pMytest)(void );

int main(void) {

    void *handle = NULL;
    char *myso = "./mylib.so";
    dlerror();
    if((handle = dlopen(myso, RTLD_NOW)) == NULL) {
        printf("dlopen - %sn", dlerror());
        exit(-1);
    }
     
    printf("success\n");
    
    pMytest = (void(*)(void))dlsym(handle, "feng");
    
    printf("error:%s\n", dlerror());
    printf("success end\n");
    pMytest();
    return 0;
}
           
g++ -o dlopen_test dlopen_test.cpp -ldl -rdynamic
           

運作可得到:1111111

注意so中的函數要用到extern "C",否則運作./dlopen_test會報undefined symbol dlsym的錯誤,因為c++編譯後的檔案會把函數名改名(為了實作重載功能),用extern "C"聲明後,就會使用c的方式進行編譯,編譯後的檔案中仍然是定義的函數名,可以通過nm來看so中函數的名稱。

如果不加extern "C“

dlopen、dlsym的簡單使用

加上後:

dlopen、dlsym的簡單使用

繼續閱讀