2017-04-03 108 views
0

所以我試圖在運行時在C++中加載一個.dylib文件並調用其中的一個函數。它似乎沒有任何問題加載文件,但當我嘗試創建一個函數指針「打印」功能它的結果是NULL。C++在運行時加載dylib函數錯誤

這裏是我的代碼:

/* main.cpp */ 

#include <iostream> 
#include <string> 
#include <dlfcn.h> 
#include "test.hpp" 

int main(int argc, const char * argv[]) { 
    std::string path = argv[0]; 
    std::size_t last = path.find_last_of("/"); 

    // get path to execution folder 
    path = path.substr(0, last)+"/"; 

    const char * filename = (path+"dylibs/libtest.dylib").c_str(); 

    // open libtest.dylib 
    void* dylib = dlopen(filename, RTLD_LAZY); 

    if (dylib == NULL) { 
     std::cout << "unable to load " << filename << " Library!" << std::endl; 
     return 1; 
    } 

    // get print function from libtest.dylib 
    void (*print)(const char * str)= (void(*)(const char*))dlsym(dylib, "print"); 

    if (print == NULL) { 
     std::cout << "unable to load " << filename << " print function!" << std::endl; 
     dlclose(dylib); 
     return 2; 
    } 

    // test the print function 
    print("Herro Word!"); 

    dlclose(dylib); 
    return 0; 
} 

測試dylib headerfile

/* test.hpp */ 

#ifndef test_hpp 
#define test_hpp 

void print(const char * str); 

#endif 

的dylib C++文件

#include <iostream> 
#include "test.hpp" 

void print(const char * str) { 
    std::cout << str << std::endl; 
} 

運行時,輸出爲:

unable to load /Users/usr/Library/Developer/Xcode/DerivedData/project/Build/Products/Debug/dylibs/libtest.dylib print function! 
Program ended with exit code: 2 

我對C++很陌生,以前從未加載過dylib。任何幫助將非常感激!

回答

2

嘗試使用extern "C"來限定print函數聲明,以避開可能正在進行的名稱損壞。

下面是關於這一主題的好文章:http://www.tldp.org/HOWTO/C++-dlopen/theproblem.html(頁解決方案討論以下)

+0

問題解決了!謝謝! – weirddan

+0

@weirddan我的榮幸! –