#ifndef TestDll_H_ #define TestDll_H_ #ifdef MYLIBDLL #define MYLIBDLL extern "C" _declspec(dllimport) #else #define MYLIBDLL extern "C" _declspec(dllexport) #endif MYLIBDLL int Add(int plus1, int plus2); //You can also write like this: //extern "C" { //_declspec(dllexport) int Add(int plus1, int plus2); //}; #endif
#include "stdafx.h" #include "testdll.h" #include <iostream> using namespace std; int Add(int plus1, int plus2) { int add_result = plus1 + plus2; return add_result; }
LIBRARY "MyDLL" EXPORTS Add @1
dllmain.cpp代码如下:
// dllmain.cpp : 定义 DLL 应用程序的入口点。 #include "stdafx.h" BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }最后,编译生成MyDLL.dll文件和MyDLL.lib文件。
// UseDll.cpp : 定义控制台应用程序的入口点。 // #pragma comment (lib,"MyDLL.lib") #include "stdafx.h" #include <iostream> using namespace std; extern "C" _declspec(dllimport) int Add(int plus1, int plus2); //或者直接在工程的Setting->Link页中设置导入MyDll.lib既可 int _tmain(int argc, _TCHAR* argv[]) { int a = 20; int b = 30; cout<<"a+b="<<Add(a, b)<<endl; getchar(); return 0; }
// UseDll.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <windows.h> using namespace std; typedef int (*AddFunc)(int a,int b); int _tmain(int argc, _TCHAR* argv[]) { HINSTANCE hInstLibrary = LoadLibrary(_T("MyDLL.dll"));//注意此处必须有_T()函数。 if (hInstLibrary == NULL) { FreeLibrary(hInstLibrary); cout<<"LoadLibrary error!"<<endl; getchar(); return 0; } AddFunc _AddFunc = (AddFunc)GetProcAddress(hInstLibrary, "Add"); if (_AddFunc == NULL) { FreeLibrary(hInstLibrary); cout<<"GetProcAddress error!"<<endl; getchar(); return 0; } cout <<"a+b="<<_AddFunc(20, 30) << endl; getchar(); FreeLibrary(hInstLibrary); return 0; }
Cyper的笔记,第二步静态链接报如下错误
1>------ Build started: Project: testdll, Configuration: Debug Win32 ------解决:
// UseDll.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; #pragma comment (lib,"MyDLL.lib") extern "C" _declspec(dllimport) int Add(int plus1, int plus2); //或者直接在工程的Setting->Link页中设置导入MyDll.lib既可 int _tmain(int argc, _TCHAR* argv[]) { int a = 20; int b = 30; cout<<"a+b="<<Add(a, b)<<endl; getchar(); return 0; }把#prama这一行移到stdafx.h下面就没有错了(折腾了很久才试出来 )