日度归档:2009 年 09 月 30 日

Linux下动态加载链接库

必须包含头文件 dlfcn.h。

使用到dlopen, dlclose, dlsym 3个主要函数,dlerror可以获取加载中遇到的错误的字符串。

下面给出部分代码,来自最新版homeserver:

	DBG("Loading plugin [%s]", name );
#ifdef __WIN32__
	p->handle = LoadLibrary( path );
	if( p->handle ){
		p->entry = (plugin_entry) GetProcAddress( p->handle,"plugin_entry");//
		p->cleanup = (plugin_entry) GetProcAddress( p->handle,"plugin_cleanup");//
	}
	if( !p->handle || p->entry==NULL ){
		DBG("# Loading plugin: %s failed: %d", path, GetLastError() );
#else
//linux
	p->handle = (int)dlopen( path, RTLD_LAZY );
	if( p->handle ){
		p->entry = (plugin_entry) dlsym( (void*)p->handle,"plugin_entry");//
		p->cleanup = (plugin_entry) dlsym( (void*)p->handle,"plugin_cleanup");//
	}
	if( !p->handle || p->entry==NULL ){
		DBG("# Loading plugin: %s failed: %s", path, dlerror() );
#endif

homeserver的源代码下载链接:

homeserver090930