J'essaie donc de charger un fichier .dylib à l'exécution en C++ et d'y appeler une fonction. Il ne semble pas y avoir de problème lors du chargement du fichier mais lorsque j'essaie de créer un pointeur de fonction pour la fonction "print", son résultat est NULL.C++ chargement des fonctions dylib à l'exécution
Voici mon code:
/* 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;
}
Test dylib headerfile
/* test.hpp */
#ifndef test_hpp
#define test_hpp
void print(const char * str);
#endif
le dylib C++ fichier
#include <iostream>
#include "test.hpp"
void print(const char * str) {
std::cout << str << std::endl;
}
la sortie lors de l'exécution est:
unable to load /Users/usr/Library/Developer/Xcode/DerivedData/project/Build/Products/Debug/dylibs/libtest.dylib print function!
Program ended with exit code: 2
Je suis assez nouveau en C++ et n'ai jamais chargé de dylibs auparavant. Toute aide serait très appréciée!
qui ont fixé le! Merci! – weirddan
@weirddan Mon plaisir! –