c ++在运行时错误加载dylib函数
c++ loading dylib functions at runtime error
所以我试图在运行时用 C++ 加载一个 .dylib 文件并在其中调用一个函数。加载文件似乎没有任何问题,但是当我尝试创建指向 "print" 函数的函数指针时,结果为 NULL。
这是我的代码:
/* 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头文件
/* 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++ 的新手,之前从未加载过动态库。任何帮助将不胜感激!
尝试使用 extern "C"
限定 print
函数声明,以绕过可能发生的名称重整。
这里有一篇关于该主题的好文章:http://www.tldp.org/HOWTO/C++-dlopen/theproblem.html(解决方案讨论在下一页)
所以我试图在运行时用 C++ 加载一个 .dylib 文件并在其中调用一个函数。加载文件似乎没有任何问题,但是当我尝试创建指向 "print" 函数的函数指针时,结果为 NULL。
这是我的代码:
/* 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头文件
/* 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++ 的新手,之前从未加载过动态库。任何帮助将不胜感激!
尝试使用 extern "C"
限定 print
函数声明,以绕过可能发生的名称重整。
这里有一篇关于该主题的好文章:http://www.tldp.org/HOWTO/C++-dlopen/theproblem.html(解决方案讨论在下一页)