新建工程,选Win32 Dynamic-Link Library,工程名为dll例子,然后选A DLL that exports some symbols,完成.
工程已经有了一个类CDll,一个变量nDll和一个函数fnDll.
在类CDll中添加例子函数f.
在dll例子.h中添加
#ifdef __cplusplus
extern "C" {
#endif
和
#ifdef __cplusplus
}
#endif
以下是dll例子.h的代码:
//手动添加 #ifdef __cplusplus // If used by C++ code, extern "C" { // we need to export the C interface #endif #ifdef DLL_EXPORTS #define DLL_API __declspec(dllexport) #else #define DLL_API __declspec(dllimport) #endif // This class is exported from the dll例子.dll class DLL_API CDll { public: CDll(void); // TODO: add your methods here. int f(); }; extern DLL_API int nDll; DLL_API int fnDll(void); //手动添加 #ifdef __cplusplus } #endif
以下是dll例子.cpp的代码:
#include "stdafx.h" #include "dll例子.h" BOOL APIENTRY DllMain( HANDLE 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; } // This is an example of an exported variable DLL_API int nDll=0; // This is an example of an exported function. DLL_API int fnDll(void) { return 42; } // This is the constructor of a class that has been exported. // see dll例子.h for the class definition CDll::CDll() { return; } int CDll::f() { return 1; }
下面演示静态链接:
新建win32控制台应用程序,选择支持MFC.
将dll例子.h, .dll和.lib拷入工程文件夹中.程序内容如下:
#include "stdafx.h" #include "隐式链接.h" #include "dll例子.h" //包括头文件 #pragma comment(lib, "dll例子.lib") //链接lib库 #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // The one and only application object CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { cout<<nDll<<endl; cout<<fnDll()<<endl; CDll c; cout<<c.f()<<endl; return 0; }
下面演示动态链接:
新建win32控制台应用程序,选择支持MFC.
程序内容如下:
#include "stdafx.h" #include "显式链接.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // The one and only application object CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { HINSTANCE hDLL; hDLL = AfxLoadLibrary("dll例子.dll"); int* p = (int*)GetProcAddress(hDLL,"nDll"); cout<<*p<<endl; typedef int (* dllfunc)(void); dllfunc pF = (dllfunc)::GetProcAddress(hDLL, "fnDll"); cout<<pF()<<endl; return 0; }
怎么导出类不知道,如果你知道的话,请告诉我.