Skip to content

Instantly share code, notes, and snippets.

@KarimIO
Created April 2, 2018 00:37
Show Gist options
  • Save KarimIO/e7e6bcbe246d0f9a8b742220437ac9b3 to your computer and use it in GitHub Desktop.
Save KarimIO/e7e6bcbe246d0f9a8b742220437ac9b3 to your computer and use it in GitHub Desktop.
DLL Class Delete Issue
#include "lib.hpp"
#include <iostream>
Lib::Lib() {
std::cout << "Lib\n";
}
void Lib::print() {
std::cout << "Print\n";
}
Lib::~Lib() {
std::cout << "~Lib\n";
}
void *create() {
return new Lib();
}
void destroy(LibBase *l) {
delete l;
}
#pragma once
#include "lib_int.hpp"
class Lib : public LibBase {
public:
Lib();
virtual void print();
~Lib();
};
#pragma once
class LibBase {
public:
virtual void print() = 0;
virtual ~LibBase() = 0;
};
extern "C" {
void *create();
void destroy(LibBase *l);
}
#include "lib_int.hpp"
#include <iostream>
#include <dlfcn.h>
#define LoadDLL(path) void *lib_handle = dlopen(("./lib"+std::string(path)+".so").c_str(), RTLD_LAZY); \
if (!lib_handle) {\
std::cout << "Failed to load " << path << ": " << dlerror() << "!\n"; \
return 1;\
}
#define LoadDLLFunction(string) dlsym(lib_handle, string);
int main() {
LoadDLL("test");
LibBase *(*pfnCreate)() = (LibBase* (*)())LoadDLLFunction("create");
if (!pfnCreate) {
std::cout << "Failed to get create() from library.\n";
return 1;
}
void (*pfnDestroy)(LibBase *) = (void (*)(LibBase *))LoadDLLFunction("destroy");
if (!pfnDestroy) {
std::cout << "Failed to get destroy() from library.\n";
return 1;
}
LibBase *l = pfnCreate();
l->print();
pfnDestroy(l);
std::cout << "Leaving Main\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment