Dll 库 DEF文件详解

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

1、为在函数声明中加上__declspec(dllexport),这里不再举例说明;

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


 首先创建 一个DLL程序,.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 <iostream>
#include <windows.h>

using namespace std;

typedef int (__stdcall *FUN)(int, int);
HINSTANCE hInstance;
FUN   fun;

int main()
{
       hInstance = LoadLibrary("DLLTestDef.dll");
       if(!hInstance)
           cout << "Not Find this Dll" << endl;
       fun = (FUN)GetProcAddress(hInstance, MAKEINTRESOURCE(1));
       if (!fun)
       {
              cout << "not find this fun" << endl;
       }
       cout << fun(1, 2) << endl;
       FreeLibrary(hInstance);
       return 0;
}

如:
LIBRARY Step01


EXPORTS
acrxEntryPoint PRIVATE @1
acrxGetApiVersion PRIVATE @2


说明:
.def文件的规则为:

  (1)LIBRARY语句说明.def文件相应的DLL为Step01;

  (2)EXPORTS语句后列出要导出函数的名称。可以在.def文件中的导出函数名后加@n,表示要导出函数的序号为n(在进行函数调用时,这个序号将发挥其作用);

  (3).def 文件中的注释由每个注释行开始处的分号 (;) 指定,且注释不能与语句共享一行。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/zohowe/archive/2009/05/02/4143649.aspx

自己测试

// TestDll.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
typedef int(__stdcall *FUN)( int ,int  );
HINSTANCE hInstance;
FUN fun;
int _tmain(int argc, _TCHAR* argv[])
{
 hInstance = LoadLibrary(_T("DllTest.dll"));
 if( !hInstance )
 {
  cout<<_T("Not find DllTest.dll!") <<endl;
 }
 fun = (FUN)GetProcAddress( hInstance,(LPCSTR) MAKEINTRESOURCE(2));
 if( !fun )
 {
  cout<<"Not find the Function~"<<endl;
 }
 cout<<fun( 1, 2 );
 FreeLibrary( hInstance );
 getchar();
 return 0;
}

生成DLL库

// DllTest.cpp : 定义 DLL 应用程序的入口点。
//

#include "stdafx.h"


#ifdef _MANAGED
#pragma managed(push, off)
#endif
/*-------------------------------------------------------------------------------
创建两个导出函数
-------------------------------------------------------------------------------*/
int __stdcall Add( int a, int b )
{
 return a + b;
}

int __stdcall Sub( int a, int b )
{
 return a - b;
}


BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
      )
{
    return TRUE;
}

#ifdef _MANAGED
#pragma managed(pop)
#endif

 

DEF文件:

LIBRARY "DllTest"
EXPORTS
Add @1
Sub

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值