QLibrary详解

#include <QLibrary>

int a=1,b=2,c=6;
typedef void (*myfun)(int,int,int *); // 定义导出函数类型

QLibrary hdll( "test01.dll" ); //加载dll,当前目录
if(hdll.load())
{
	myfun fun1 = (myfun)hdll.resolve("MYSUB"); //用resolve来解析fun1函数
	if ( fun1 ) //解析成功则进行运算并提示相关信息
	{
		fun1(a,b,&c);
		QString qss=tr("dll加载成功!\n 1+2=")+QString::number(c,10);
	}
}

 QT 源码之 QLibrary 。

1、win下动态库调用有关的函数包括:

(1)LoadLibrary,装载动态库。

(2)GetProcAddress,猎取要引入的函数,将符号名或标识号转换为DLL内部地址。

(3)FreeLibrary,释放动态链接库。

2、unix上与动态库调用有关的函数包括:

(1)_打开动态链接库:dlopen,函数原型void *dlopen (const char *filename, int flag);

dlopen用于打开指命名字(filename)的动态链接库,并前往操作句柄。

(2)取函数执行地址:dlsym,函数原型为: void *dlsym(void *handle, char *symbol);

dlsym根据动态链接库操作句柄(handle)与符号(symbol),前往符号对应的函数的执行代码地址。

(3)关闭动态链接库:dlclose,函数原型为: int dlclose (void *handle);

dlclose用于关闭指定句柄的动态链接库,只有当此动态链接库的运用计数为0时,才会真正被系统卸载。

(4)动态库毛病函数:dlerror,函数原型为: const char *dlerror(void); 当动态链接库操作函数执行失利时,dlerror能够前往犯错信息,前往值为NULL时表示操作函数执行成功

下面是我用vc编写的一个动态库中的函数add:

extern "C" __declspec(dllexport) int __stdcall add(int a,int b)  
{  
    return a+b;  

下面我就用QLibrary来调用一下:

QLibrary lib("QtDllTest.dll");  
if (lib.load())  
{  
    typedef int(*AddFunction)(int a,int b);  
    AddFunction Add=(AddFunction)lib.resolve("add");  
    if (!Add)  
    {  
        cout<<"failed"<<endl;  
    }  
    else  
    {  
       int m;  
       m=Add(1,1); //来个计算1+1  
       cout<<"result:"<<m<<endl;  
    }  
    lib.unload();  
}  
else  
{  
    cout<<"failed"<<endl;  

首先将目录切换到QTDIR\src\corelib\plugin,这里面就是QLibrary实现的源代码,打开qlibrary_p.h(熟悉了Qt的经常运用手法,就知道,这就是QLibrary内部实现的代码),能够看到

bool load_sys();  
bool unload_sys();  
void *resolve_sys(const char *); 
三个函数。在qlibrary.cpp中能够找到调用这三个函数的地方

bool QLibrary::load ()调用了load_sys;  
bool QLibrary::unload ()调用了unload_sys;  
void * QLibrary::resolve ( const char * symbol )调用了resolve_sys 
然则并没有找到这三个函数的实现,这是这么回事呢?

打开QTDIR\src\corelib\plugin\plugin.pri资料,

win32 {  
 SOURCES += plugin/qlibrary_win.cpp  
}  
unix {  
 SOURCES += plugin/qlibrary_unix.cpp  

原来如此啊。

咱们仔细看下qlibrary_win.cpp资料,load_sys函数调用了LoadLibrary,unload_sys调用了FreeLibrary,resolve_sys调用了GetProcAddress。

而在qlibrary_unix.cpp资料中,各种linux平台又分好多种。然则基本上load_sys调用了dlopen,unload_sys调用了dlclose,resolve_sys调用了dlsym。

在HPUX中dlopen对应shl_load,dlclose对应shl_unload,dlsym对应shl_findsym。

 

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值