在Windows平台下,動態連結庫(Dynamic Link Library,簡稱DLL)是一種常用的元件化技術,它可以讓多個程式共享同一個函數庫,減少了重複程式碼的開發,並且可以實現模組升級、替換等操作。而在寫DLL時,DllMain是最重要的一個函數。本篇文章將探討如何使用Golang實作DllMain函數。
一、DllMain概述
在Windows平台上,當DLL被載入或卸載時,作業系統會自動呼叫DllMain函數。 DllMain函數的原型如下:
BOOL WINAPI DllMain(HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpReserved);
其中,hinstDll參數是DLL自身的實例句柄,fdwReason參數表示DLL被載入、卸載或其他操作的原因,可以取以下取值:
go build -buildmode=c-shared -o example.dll example.go
package main import "C" var ( hInstance C.HMODULE ) //export DllMain func DllMain(hinstDLL C.HMODULE, fdwReason C.DWORD, lpvReserved C.LPVOID) C.BOOL { switch fdwReason { case C.DLL_PROCESS_ATTACH: hInstance = hinstDLL // do initialize job here case C.DLL_PROCESS_DETACH: // do cleanup job here case C.DLL_THREAD_ATTACH: // do something when a new thread created case C.DLL_THREAD_DETACH: // do something when a thread was ended } return 1 }
set CGO_ENABLED=1 set CGO_CFLAGS=-Wall go build -buildmode=c-shared -o example.dll example.go
#include <windows.h> #include <stdio.h> typedef BOOL(WINAPI* DllMainFunc)(HINSTANCE, DWORD, LPVOID); int main() { HMODULE hDll = LoadLibrary("example.dll"); if (hDll == NULL) { printf("Load library failed.\n"); } else { printf("Load library succeed.\n"); DllMainFunc pDllMain = (DllMainFunc)GetProcAddress(hDll, "DllMain"); if (pDllMain == NULL) { printf("Get function address failed.\n"); } else { printf("Get function address succeed.\n"); (*pDllMain)(hDll, DLL_PROCESS_ATTACH, NULL); (*pDllMain)(hDll, DLL_PROCESS_DETACH, NULL); } FreeLibrary(hDll); } return 0; }
以上是如何使用Golang實作DllMain函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!