一、用vc编写dll文件
首先建立一个Win32 Dynamic-Link Library工程,在工程中添加要写的代码。
注意:与普通工程不同的是在dll工程中声明函数或者类时要在前面写上_declspec(dllexport),如:
class _declspec(dllimport) student
{
}
c语言的导出格式为extern "C" _declspec(dllexport),如函数void fun(),声明的时候要写成extern "C" _declspec(dllexport) void fun().
如:
DllTest.h文件
#ifndef __DLLTEST_H__
#define __DLLTEST_H__
extern "C" _declspec(dllexport) int MyMax(int a, int b);
#endif
DllTest.cpp文件
#include "stdafx.h"
#include
#include "DllTest.h"
BOOL APIENTRY DllMain( HANDLE hModule,
{
}
int MyMax(int a, int b)
{
}
二.自制dll文件的调用
大概有两种方法:
1.用LoadLibrary方法动态加载dll
在函数调用前,首先声明dll库的实例变量,如HINSTANCE gLib = NULL;
然后声明要调用函数的函数指针,在用LoadLibrary找到该函数的地址,然后就可以调用的。程序运行时要保证dll文件和要调用的exe在同一个目录下。
例如:
#include "stdafx.h"
#include
HINSTANCE gLib = NULL;
typedef int (*TheMax)(int a, int b);
int main(int argc, char* argv[])
{
}
2.通过头文件和lib文件加载dll
把要调用函数的.h文件和工程中生成的lib文件拷到工程中去。然后再vc中添加lib库,方法:工程->设置->连接,在对象/库模块一栏的最后添加lib文件名,或者直接在代码中添加 #pragma comment(lib, "you.lib")即可,然后引入头文件即可调用。编译好后把dll文件和exe文件放在同一目录下即可运行。
例如:
#include "stdafx.h"
#include "DllTest.h"
#pragma comment(lib, "DllTest.lib")
int main(int argc, char* argv[])
{
}