VC6 静态与动态加载Dll [示例代码]

1、DLL源代码

MyDll.h

view plaincopy to clipboardprint?
//  
// MyDll.h  
// 声明函数  
int _stdcall Add(int a,int b);  
int _stdcall Sub(int a,int b); 
//
// MyDll.h
// 声明函数
int _stdcall Add(int a,int b);
int _stdcall Sub(int a,int b);

MyDll.cpp

view plaincopy to clipboardprint?
//  
// MyDll.pp  
// 声明实现  
#include "MyDll.h"  
int _stdcall Add(int a,int b)  
{  
    return a+b;  
}  
int _stdcall Sub(int a,int b)  
{  
    return a-b;  

//
// MyDll.pp
// 声明实现
#include "MyDll.h"
int _stdcall Add(int a,int b)
{
 return a+b;
}
int _stdcall Sub(int a,int b)
{
 return a-b;
}

MyDll.def

view plaincopy to clipboardprint?
; MyDll为工程名  
LIBRARY MyDll  
; 在这里声明需要导出的函数  
EXPORTS  
Add  
Sub 
; MyDll为工程名
LIBRARY MyDll
; 在这里声明需要导出的函数
EXPORTS
Add
Sub

2、Exe测试代码

演示动态与静态加载的方法,看代码吧!

view plaincopy to clipboardprint?
void CTestDlg::OnBtnStatic()   
{  
    // TODO: Add your control notification handler code here  
    // 静态加载的方法:  
    // 1、添加头文件 #include "MyDll.h"  
    // 2、引入Lib库  #pragma comment(lib, "MyDll.lib")  
    // 3、这样就可以直接使用MyDll.h中导入的函数  
    CString str;  
    str.Format("静态加载: 1+1=%d 1-1=%d", Add(1,1), Sub(1,1));  
    MessageBox(str);  
}  
void CTestDlg::OnBtnDynamic()   
{  
    // TODO: Add your control notification handler code here  
    // 动态加载的方法:  
    // 不需要引入头文件与lib文件,仅需要一个dll即可  
    // 注意这里的条约调用约定_stdcall不要忘记加(不然会引会esp出错)  
      
    typedef int (_stdcall *ADDPROC)(int, int);  
    typedef int (_stdcall *SUBPROC)(int, int);  
    HINSTANCE handle;  
    handle = LoadLibrary("MyDll.dll");  
    if(handle)  
    {  
        // GetProcAddress第二个参数有两种方法:  
        // 1、通过DLL中的函数名  
        // 2、通过Depend工具中Ordinal索引值来查看  
        ADDPROC MyAdd = (ADDPROC)GetProcAddress(handle, "Add");  
        SUBPROC MySub = (ADDPROC)GetProcAddress(handle, MAKEINTRESOURCE(2));  
        if( !MyAdd )  
        {  
            MessageBox("函数Add地址获取失败!");  
            return;  
        }  
        if( !MySub )  
        {  
            MessageBox("函数Sub地址获取失败!");  
            return;  
        }  
        CString str;  
        str.Format("动态加载: 1+1=%d 1-1=%d", MyAdd(1,1), MySub(1,1));  
        MessageBox(str);  
    }  
    FreeLibrary(handle);  

 

ZZ:http://blog.csdn.net/wangningyu/archive/2010/04/09/5466579.aspx

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值