一、生成DLL
1. 新建DLL工程
在VS中,新建一个空的项目,选Win32 Console Application,新建完后修改工程属性:把生成EXE改为生成DLL
2. 源代码:
ShowInfo.h
#define SHOWINFO_API __declspec(dllexport)
extern "C" SHOWINFO_API void fnShowInfo(void);
ShowInfo.c:
#include "ShowInfo.h"
#include <stdio.h>
SHOWINFO_API void fnShowInfo(void)
{
printf("Crab\n");
}
1. 新建工程
新建一个Win32 Console Application,选择空的工程。
2. 源代码:
main.cpp
#include <windows.h>
#include <iostream>
using namespace std;
typedef void (*DllFn)(void);
int main()
{
HINSTANCE hInst = LoadLibrary(TEXT("ShowInfo.dll"));
if(hInst)
{
DllFn a =(DllFn) GetProcAddress(hInst,"fnShowInfo");
if(a)
a();
else
cout<<"ERROR on GetProcAddress"<<endl;
FreeLibrary(hInst);
}
else
cout<<"Error on Load library"<<endl;
}
(用 LoadLibrary 可能会出现 “不能将参数 1 从‘const char [13]’转换为‘LPCWSTR’”的错误,这时需要用到TEXT()函数。)
由于用了LoadLibrary函数,所以dll的文件名可以改变,只要文件名和LoadLibrary中的参数一样,就可以了。
3. 将上面工程生成的dll.dll文件复制到此工程的目录下,保证源文件与DLL文件在同一目录下。如果生成的EXE文件要直接运行,则要保证EXE文件与DLL文件在同一目录下。
4. 编译连接,执行。
1. 新建DLL工程
在VS中,新建一个空的项目,选Win32 Console Application,新建完后修改工程属性:把生成EXE改为生成DLL
2. 源代码:
ShowInfo.h
#define SHOWINFO_API __declspec(dllexport)
extern "C" SHOWINFO_API void fnShowInfo(void);
ShowInfo.c:
#include "ShowInfo.h"
#include <stdio.h>
SHOWINFO_API void fnShowInfo(void)
{
printf("Crab\n");
}
3. 编译连接,生成dll.dll文件
(在ShowInfo.h中声明函数的时候要加上 extern "C", 因为如果该函数可能会被c++ 程序调用。)
1. 新建工程
新建一个Win32 Console Application,选择空的工程。
2. 源代码:
main.cpp
#include <windows.h>
#include <iostream>
using namespace std;
typedef void (*DllFn)(void);
int main()
{
HINSTANCE hInst = LoadLibrary(TEXT("ShowInfo.dll"));
if(hInst)
{
DllFn a =(DllFn) GetProcAddress(hInst,"fnShowInfo");
if(a)
a();
else
cout<<"ERROR on GetProcAddress"<<endl;
FreeLibrary(hInst);
}
else
cout<<"Error on Load library"<<endl;
}
(用 LoadLibrary 可能会出现 “不能将参数 1 从‘const char [13]’转换为‘LPCWSTR’”的错误,这时需要用到TEXT()函数。)
由于用了LoadLibrary函数,所以dll的文件名可以改变,只要文件名和LoadLibrary中的参数一样,就可以了。
3. 将上面工程生成的dll.dll文件复制到此工程的目录下,保证源文件与DLL文件在同一目录下。如果生成的EXE文件要直接运行,则要保证EXE文件与DLL文件在同一目录下。
4. 编译连接,执行。