1 2 3 4 5 6 7 8 9 10 11 12 13 | #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 |
dllmain.cpp代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 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; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // 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; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // 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 ------解决:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // 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; } |
联系客服