如何调用dll文件中的函数

来源:互联网 发布:淘宝永久封号怎么激活 编辑:程序博客网 时间:2024/05/19 12:13
动态链接主要是利用LoadLibrary、GetProcAddress、FreeLibrary这三个api

LoadLibrary
HINSTANCE LoadLibrary(LPCTSTR lpLibFileName);
The LoadLibrary function maps the specified executable module into the address space of the calling process. 
这个函数就是映射可执行模块的地址到调用这个函数的进程中,以便这个进程能够调用可执行模块中的函数。
输入参数: lpLibFileName 指向一个可执行模块的名字的字符串,在这里也就是指向"sqlite3.dll"的字符指针,你也可以加路径,请注意要用back slashes(\)代替forward slashes(/)。具体的请参看MSDN。
返回值:成功的话就返回这个可执行模块的句柄(下面要用),否则返回NULL。
GetProcAddress
FARPROC GetProcAddress(  HMODULE hModule,  LPCSTR lpProcName );
The GetProcAddress function returns the address of the specified exported dynamic-link library (DLL) function.
这个函数返回动态链接库(DLL)中指定函数的地址,为了下面可以调用这个指定的函数。
输入参数:
hModule 就是调用LoadLibrary得到的句柄。
lpProcName字符指针,指向函数名(这个函数必须是dll中定义的函数)。
返回值:函数指针,是对应上面函数名的函数的入口地址。
FreeLibrary
BOOL FreeLibrary( HMODULE hLibModule  );
The FreeLibrary function decrements the reference count of the loaded dynamic-link library (DLL) module. When the reference count reaches zero, the module is unmapped from the address space of the calling process and the handle is no longer valid. 
这个函数就是释放我们load的dll模块。当有多次load的时候,我们一次释放一个。
输入参数:就是上面调用LoadLibrary得到的句柄。
返回值:失败为0,否则为非0
下面给出一个小例子
typedef int(*SQLITE3_OPEN)(const char *filename,sqlite3 **ppdb);
SQLITE3_OPEN sqlite3_open;
HINSTANCE hdll;
int init_dll_function(void)
{
      hdll=LoadLibrary("sqlite3.dll");
      if(hdll==NULL){printf("Error to LoadLibrary!\n");return 1;}
      sqlite3_open=(SQLITE3_OPEN)GetProcAddress(hdll,"sqlite3_open"); 
      if(sqlite3_open==NULL){
            printf("Error!\n");
            return 1;
      }
if(!FreeLibrary(hdll)){
return 1;
}
return 0;
}

0 2