2017-04-03 3 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 
,691 여기

내 코드입니다

저는 C++을 처음 접했고 전에 dylib를로드 한 적이 없습니다. 어떤 도움을 많이 주시면 감사하겠습니다!

답변

2

가능성이있는 맹 글링을 해결하기 위해 과 함께 print 함수 선언을 정규화하여보십시오.

여기에 주제에 대한 좋은 기사입니다 : http://www.tldp.org/HOWTO/C++-dlopen/theproblem.html

+0

가 고정 그 (페이지 솔루션 토론 다음)! 감사! – weirddan

+0

@weirddan 내 기쁨! –