DLL的生成和使用
DLL的生成和使用
==========================
一、生成DLL动态库文件
1. 新建项目工程:DLLDemo(Visual C++ -> Win32 Console Application)
Application Settings -> type -> 选择DLL (Finished)
2. 添加 MyCode.h && MyCode.cpp 文件
MyCode.h
#ifndef _MYCODE_H_ #define _MYCODE_H_ #ifdef DLLDEMO1_EXPORTS #define EXPORTS_DEMO _declspec( dllexport ) #else #define EXPORTS_DEMO _declspec(dllimport) #endif extern "C" EXPORTS_DEMO int Add (int a , int b); #endif
MyCode.cpp
#include "stdafx.h" #include "MyCode.h" int Add ( int a , int b ) { return ( a + b ); }
3. Build 生成DLL文件(附带lib文件)

二、使用DLL动态库(隐式调用 & 显示调用)
1. 在DLLDemo项目下新建工程(TestRun)(Visual C++ -> Win32 Console Application)
TestRun.cpp
// TestRun.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <windows.h> //加载动态库(通过lib隐式加载) 01 //using namespace std; //#pragma comment(lib, "DLLDemo.lib") //extern "C" _declspec(dllimport) int Add(int a, int b); //加载动态库(显示加载) 01 using namespace std; typedef int (*AddFunc)(int a, int b); int _tmain(int argc, _TCHAR* argv[]) { //加载动态库(通过lib隐式加载) 02 //cout<<Add(2, 3)<<endl; //加载动态库(显示加载) 02 HINSTANCE hDll = LoadLibrary("..\\Release\\DLLDemo.dll"); if (hDll != NULL) { AddFunc add = (AddFunc)GetProcAddress(hDll, "Add"); if (add != NULL) { cout<<add(2, 3)<<endl; } FreeLibrary(hDll); } system("pause"); return 0; }
warn:(字符集报错)
TestRun.cpp(25): error C2664: 'LoadLibraryW' : cannot convert parameter 1 from 'const char [23]' to 'LPCWSTR'
解决:(配置)
Character Set ( Configuration Properties -> General -> Project Defaults ) // Unicode 改为 多字节字符集 Use Unicode Character Set -> Use Multi-Byte Character Set
--- THE END !!
浙公网安备 33010602011771号