您当前的位置: 首页 > 

phymat.nico

暂无认证

  • 4浏览

    0关注

    1967博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

DLL中导出函数的声明有两种方式

phymat.nico 发布时间:2015-01-08 10:46:41 ,浏览量:4

 本文引用自:VC编程时DLL中导出函数的声明有两种方式

一种方式是:在函数声明中加上__declspec(dllexport);

另外一种方式是:采用模块定义(.def)文件声明,(.def)文件为链接器提供了有关被链接程序的导出、属性及其他方面的信息。

方式一:在函数声明中加上__declspec(dllexport)

/// 在动态链接库程序中

/// 声明动态链接库(**.dll)的对外接口函数TestFuction

extern "C" __declspec(dllexport) int TestFuction(int nType,char *strPath,std::vector &vecData)

{

   do anything here

   return 0;

}

/// 在外部希望调用动态链接库的程序中

/// 加载动态链接库(**.dll)并调用其对外接口TestFuction

void func()

{

  //typedef与函数TestFuction类型相同的函数指针为TESTDLL

  typedef int (_cdecl * TESTDLL)(int nType,char *strPath,std::vector &vecData);

  HINSTANCE hmod;

  //加载动态链接库**.dll

  hmod =::LoadLibrary(_TEXT("dll相对路径\\**.dll"));

  if(NULL == hmod)

  {

     TRACE("加载**.dll失败");

  }

  //定义一个与函数TestFuction类型相同的函数指针lpproc

  TESTDLL lpproc;

  //搜索**.dll中函数名为TestFuction的对外接口

  lpproc = (TESTDLL)GetProcAddress (hmod,"TestFuction");

  //如果搜索成功

  if(NULL != lpproc)

  {

     int nType = 0;

     char* strPath = "Data";

     std::vector vecData;

     //通过函数指针lpproc调用**.dll的接口函数TestFuction

     int nResult = (*lpproc)(nType,strPath,vecData);

  }

  //...

  //在恰当的时候释放动态链接库**.dll

  FreeLibrary(hmod);

}

方式二:采用模块定义(.def)文件声明

首先创建 一个DLL程序(DllTestDef)

在*.cpp中

int __stdcall Add(int numa, int numb)

{

     return (numa + numb);

}

int __stdcall Sub(int numa, int numb)

{

     return (numa - numb);

}

然后创建一个.def的文件,在里面加上

;DllTestDef.lib : 导出DLL函数

;作者:----

LIBRARY DllTestDef

EXPORTS

Add @ 1

Sub @ 2

最后创建一个测试程序:.cpp文件如下:

#include

#include

using namespace std;

typedef int (__stdcall *FUN)(int, int);

HINSTANCE hInstance;

FUN   fun;

int main()

{

       hInstance = LoadLibrary("DLLTestDef.dll");

       if(!hInstance)

           cout

关注
打赏
1659628745
查看更多评论
立即登录/注册

微信扫码登录

0.0449s