2017-04-03 11 views
0

したがって、実行時に.dylibファイルをC++で読み込み、その中で関数を呼び出そうとしています。ファイルの読み込みに問題はないようですが、 "print"関数への関数ポインタを作成しようとすると結果は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

と機能の宣言を修飾すると、起こりそうな名前のマ​​ングリングが回避されます。 http://www.tldp.org/HOWTO/C++-dlopen/theproblem.html(ページ以下のソリューションの議論)

+0

それを修正:ここ

は、トピックに関する素晴らしい記事です!ありがとう! – weirddan

+0

@weirddan私の喜び! –