DLL代码:
// TestDynamic.cpp: implementation of the TestDynamic class. // ////////////////////////////////////////////////////////////////////// #include "TestDynamic.h" #include <windows.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } __stdcall int Plus(int x, int y) { return x + y; } __stdcall int Sub(int x, int y) { return x - y; } __stdcall int Mul(int x, int y) { return x * y; } __stdcall int Div(int x, int y) { return x / y; }
// TestDynamic.h: interface for the TestDynamic class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_TESTDYNAMIC_H__5BBAD36E_608D_4D94_B6D6_19404806F6AE__INCLUDED_) #define AFX_TESTDYNAMIC_H__5BBAD36E_608D_4D94_B6D6_19404806F6AE__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 extern "C" __declspec(dllexport) __stdcall int Plus(int x, int y); extern "C" __declspec(dllexport) __stdcall int Sub(int x, int y); extern "C" __declspec(dllexport) __stdcall int Mul(int x, int y); extern "C" __declspec(dllexport) __stdcall int Div(int x, int y); #endif // !defined(AFX_TESTDYNAMIC_H__5BBAD36E_608D_4D94_B6D6_19404806F6AE__INCLUDED_)
调用程序主代码:
// TestDll.cpp : Defines the entry point for the console application. // 隐式调用 #include "stdafx.h" #pragma comment(lib,"testDynamic.lib"); extern "C" __declspec(dllimport) __stdcall int Plus(int x, int y); extern "C" __declspec(dllimport) __stdcall int Sub(int x, int y); extern "C" __declspec(dllimport) __stdcall int Mul(int x, int y); extern "C" __declspec(dllimport) __stdcall int Miv(int x, int y); int main(int argc, char* argv[]) { int t = Plus(1,1); printf("%d ",t); return 0; }
// TestDll.cpp : Defines the entry point for the console application. // 显式调用 #include "stdafx.h" #include <windows.h> typedef int (__stdcall *lpPlus)(int, int); typedef int (__stdcall *lpSub)(int, int); typedef int (__stdcall *lpMul)(int, int); typedef int (__stdcall *lpDiv)(int, int); int main(int argc, char* argv[]) { lpPlus myPlus; lpSub mySub; lpMul myMul; lpDiv myDiv; HINSTANCE hModule = LoadLibrary("testDynamic.dll"); myPlus = (lpPlus)GetProcAddress(hModule, "Plus"); int x = myPlus(1,1); printf("%d ",x); return 0; }
PS:注意__stdcall如果DLL中没有定义为__stdcall在调用时就不要用