创建和调用dll文件简单示例(vc6)

在vc6中,新建一个Win32 Dynamic-Link Library Project.

命名为:dllexample。然后看下面的例子。

下面是dllexample.cpp:

//===================================

#include "stdafx.h"
/*
 * dll文件的输出函数声明
 */
extern "C" _declspec(dllexport) float t_max(float x, float y);
extern "C" _declspec(dllexport) float t_min(float x, float y);
/*
 * DllMain函数
 * 进程初始化和终止时都要调用此函数
 * 在这里可以分配和释放资源
 * 关于DllMain函数的详细情况这里先不讨论
 */
BOOL APIENTRY DllMain( HANDLE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
      )
{
    return TRUE;
}
/*
 * dll的输出函数定义,这里以简单的取大取小运算为例
 */
float  t_max(float x, float y)
{
 return x > y ? x : y;
}

float t_min(float x, float y)
{
 return x < y ? x : y;
}

//=================================

build一下。生成两个文件:dllexample.dll和dllexample.lib

那么如何调用呢?

有两种方法:

方法一:隐式链接

1.新建win32 工程。命名为testdll.

2.把上面生成的dllexample.lib和dllexample.dll拷贝到testdll工程目录下。

3.在Project-settings-link-Objcte/Lib中加入dllexample.lib

4.在testdll.cpp添加代码如下:

//============================

// testdll.cpp //

#include "stdafx.h"
#include "stdio.h"
/* 在合适的地方声明dll中的函数原型 */
float t_max(float x, float y);
float t_min(float x, float y);

int main(int argc, char* argv[])
{
 float x = (float)3.6, y = (float)9.8;
 float fmax = t_max(x, y);
 float fmin = t_min(x, y);
 printf("%f, %f", fmax, fmin);
 return 0;
}

//============================

build and run。输出:

9.800000, 3.600000

方法二:显式链接

本方法适合于只有dll文件没有lib文件的情况。

1.新建win32工程testdll

2.把dllexample.dll拷贝到testdll工程目录下

3.testdll.cpp代码修改如下:

//============================

// testdll.cpp //

#include "stdafx.h"
#include "stdio.h"
#include <afxwin.h>  // for HINSTANCE
int main(int argc, char* argv[])
{

 float x = (float)3.6, y = (float)9.8;
 //函数指针定义
 typedef float(*p_fun)(float x,float y);
    p_fun t_max, t_min;
    //加载dll
 HINSTANCE hDll = LoadLibrary("dllexample.dll");
 if(hDll == NULL) return 0;
    //获取函数指针
 t_max = (p_fun)GetProcAddress(hDll,"t_max");
 t_min = (p_fun)GetProcAddress(hDll,"t_min");
    //调用
 float fmax = t_max(x, y);
 float fmin = t_min(x, y);

 printf("%f, %f", fmax, fmin);
    //释放dll
 FreeLibrary(hDll);
 return 0;

}
//===========================

build and run。输出:

9.800000, 3.600000
/*=====================*/

本文适合初用dll者。

好了,今天就是这样,有事下回再说!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值