Click here to Skip to main content
15,886,799 members
Articles / Programming Languages / C++

Win32/Linux Dynamic Library Loader Class

Rate me:
Please Sign up or sign in to vote.
3.94/5 (15 votes)
12 Oct 2006CPOL2 min read 80.4K   795   42  
A class to dynamically load DLLs and SO files and call functions from them
/*
 * BCLoadLib.h - A WIN32/Linux runtime library loader.
 * Created April 17, 2006, by Michael 'Bigcheese' Spencer.
 */

#include "BCLoadLib.h"
#include <string.h>

BCLoadLib::BCLoadLib(char* libname){
	libhandle = 0;
	#ifdef WIN32
	libhandle = LoadLibrary(libname);
	#else
	// First we need to add ./ and end with .so.
	int len = strlen(libname);
	len += 6; // Add room for ./, .so, and null.
	char* name = new char[len];
	name[0] = 0;
	strcat(name, "./");
	strcat(name, libname);
	strcat(name, ".so");
	libhandle = dlopen(name, RTLD_LAZY);
	delete[] name;
	#endif

	if(!libhandle)
		throw("Library could not be loaded.");
};

BCLoadLib::~BCLoadLib(){
	if(libhandle){
		#ifdef WIN32
		FreeLibrary((HINSTANCE)libhandle);
		#else
		dlclose(libhandle);
		#endif
	}
};

void* BCLoadLib::getFunc(char* funcName){
	void* func = 0;
	if(libhandle){
		#ifdef WIN32
		func = GetProcAddress((HINSTANCE)libhandle, funcName);
		#else
		func = dlsym(libhandle, funcName);
		#endif
	}

	if(!func)
		throw("Function could not be loaded.");

	return func;
};

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions