DLL的使用

来源:互联网 发布:mysql 1054 编辑:程序博客网 时间:2024/06/11 18:08
DLL相关函数:
HINSTANCE LoadLibrary(PCTSTR pszDLLPathName); //加载DLL
BOOL FreeLibrary(HINSTANCE hinstDll); //卸载DLL
HINSTANCE GetModuleHandle(PCTSTR pszModuleName); //线程确定DLL是否已经被映射到进程的地址空间中
FARPROC GetProcAddress(HINSTANCE hinstDll,PCSTR pszSymbolName); //线程获取它要引用的符号的地址

DllMain:
DLL_PROCESS_ATTACH //dll加载时运行
DLL_PROCESS_DETACH //dll卸载时运行

dllexport与dllimport:
在c++下使用extern "C":
#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
    }
#endif

export/import函数:
#ifdef SAMPLEDLL_EXPORTS
__declspec(dllexport) bool Initialize();
__declspec(dllexport) void Uninitialize();
#else
__declspec(dllimport) bool Initialize();
__declspec(dllimport) void Uninitialize();
#endif

export/import类:
#ifdef SAMPLEDLL_EXPORTS
class __declspec(dllexport) XXX
{
}
#else
class __declspec(dllimport) XXX
{
}
#endif

expport/import变量:
#ifdef SAMPLEDLL_EXPORTS
extern __declspec(dllexport) int gIntVariable;
#else
extern __declspec(dllimport) int gIntVariable;
#endif

eg.
//定义函数指针指向DLL中export的函数
typedef bool (*initialize)();
typedef void (*uninitialize)();

int _tmain(int argc, _TCHAR* argv[])
{
    // 1. 加载DLL
    HANDLE handle = LoadLibraryA("SampleDll.dll");

    // 2. 获取DLL Export的函数
    initialize pInitialize = (initialize)GetProcAddress((HMODULE)handle, "Initialize");
    uninitialize pUninitialize = (uninitialize)GetProcAddress((HMODULE)handle, "Uninitialize");

    pInitialize();
    pUninitialize();

    // 3. 获取DLL Export的变量
    int gIntVariable = (int&)GetProcAddress((HMODULE)handle, "gIntVariable");

    // 4. 释放库
    FreeLibrary((HMODULE)handle);

    return 0;
}
0 0
原创粉丝点击