DLL专题之Dll调用

我们先写一个测试DLL,这个DLL导出两个不同调用约定的函数,然后我们试着如何调用他们.

好,首先先写一个DLL吧.(Win32动态连接库)

头文件:

#ifndef _DLLCALL_DLL_H_
#define _DLLCALL_DLL_H_

#include "windows.h"

/*---------------------------------------------------------------*/
对于不同的调用约定的函数导出,我个人认为用名字定义文件是最方便的了。
这样,你就可以直接根据函数名字或者函数序号来调用了
/*---------------------------------------------------------------*/
void __cdecl  ShowMessage1( LPCTSTR pstrMsg, LPCTSTR pstrTitle );
void __stdcall  ShowMessage2( LPCTSTR pstrMsg, LPCTSTR pstrTitle );

#endif//_DLLCALL_DLL_H_

实现文件:

#include "DllCall.h"

void __cdecl ShowMessage1( LPCTSTR pstrMsg, LPCTSTR pstrTitle )
{
 MessageBox( NULL, pstrMsg, pstrTitle, MB_OK |MB_ICONINFORMATION );
}
void __stdcall ShowMessage2( LPCTSTR pstrMsg, LPCTSTR pstrTitle )
{
 MessageBox( NULL, pstrMsg, pstrTitle, MB_OK |MB_ICONINFORMATION );
}

编译连接就好了.

然后,我们看如何调用吧.

先调用ShowMessage1吧:

void CDllDlg::OnBtnDllcall1()
{
 // TODO: Add your control notification handler code here
 typedef void (/*__cdecl*/ *lpShowMessage)
  ( LPCTSTR pstrMsg, LPCTSTR pstrTitle );       //DLL里的函数原型(C/C++默认就是__cdecl调用约定,所以可以不写)
 
 HINSTANCE hInst = NULL;              //DLL的实例句柄,在WIN32中HINSTANCE和HMODULE可以互换使用
 lpShowMessage ShowMessage;             //函数定义
 
 hInst = LoadLibrary( ".//DllCall//Debug//DllCall.dll" );    //导入DLL
 if ( !hInst ) return ;
 ShowMessage = (lpShowMessage)GetProcAddress( hInst, "ShowMessage1" );
 if ( ShowMessage )
 {
  ShowMessage( _T("Hello World!"), _T("Information") );    //调用DLL里的函数
 }
 FreeLibrary( hInst );             //释放DLL
}

然后调用ShowMessage2:

void CDllDlg::OnBtnDllcall2()
{
 // TODO: Add your control notification handler code here
 typedef void (__stdcall  *lpShowMessage)
  ( LPCTSTR pstrMsg, LPCTSTR pstrTitle );       //DLL里的函数原型
 
 HINSTANCE hInst = NULL;              //DLL的实例句柄,在WIN32中HINSTANCE和HMODULE可以互换使用
 lpShowMessage ShowMessage;             //函数定义
 
 hInst = LoadLibrary( ".//DllCall//Debug//DllCall.dll" );    //导入DLL
 if ( !hInst ) return ;
 ShowMessage = (lpShowMessage)GetProcAddress( hInst, "ShowMessage2" );
 if ( ShowMessage )
 {
  ShowMessage( _T("Hello World!"), _T("Information") );    //调用DLL里的函数
 }
 FreeLibrary( hInst );             //释放DLL
}

打完就收工了啦.记住要根据调用约定来正确调用DLL里的函数的.不然会出错的.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值