dll库生成和使用

抄自http://www.cnblogs.com/fangyukuan/archive/2010/06/20/1761464.html

1. VS2010中新建Win32-Win32项目,输入名称DllDemo

2. 选择DLL,点击完成

3. 在DllDemo.cpp中加入:

// DllDemo.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"

//使用关键字_declspec(dllexport)来声明外部引用的函数
extern "C" __declspec(dllexport) void SayHello(const char * string)
{
    ::MessageBox(NULL, string, "提示", MB_OK);
}

4. 生成解决方案

第二步,使用这个Dll库。新建控制台程序TestDll。

在TestDll.cpp中输入:

//#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;

//定义函数指针
typedef void (*SAYHELLO)(const char *);

int main()
{
    HINSTANCE hDll;

    //装载dll库
    hDll = LoadLibrary(L"DllDemo.dll");
    if (NULL == hDll){
        cout<<"加载dll失败!\n";
    }else{
        // 从dll中获取函数的入口地址
        SAYHELLO lpproc = (SAYHELLO)GetProcAddress(hDll, "SayHello");
        if (NULL != lpproc){
            //调用dll中的函数
            (*lpproc)("优衣库");
        }
        // 卸载库
        FreeLibrary(hDll);
    }
    return 0;
}

点击生成解决方案,再点击运行,运行结果如图:

(完)

posted @ 2015-07-15 13:09  凤舞十天  阅读(471)  评论(0编辑  收藏  举报