建立dll专案
新增档案
设定不使用先行标题档
dllLib.h
#ifdef dll_EXPORTS#define dll_API __declspec(dllexport)#else#define dll_API __declspec(dllimport)#endifextern “C”{ dll_API int dll_Init(); dll_API int dll_Run(unsigned char *ucPara1, int dPara2); dll_API int dll_DeInit();}
extern C将汇出 C 函式以用于 C 或 C++ 语言可执行档
建置dll档
建立空白专案来呼叫dll
新增档案
def function pointer
typedef int(*dll_Init_def)();dll_Init_def dll_Init_p = NULL;typedef int(*dll_Run_def)(unsigned char*, int);dll_Run_def dll_Run_p = NULL;typedef int(*dll_DeInit_def)();dll_DeInit_def dll_DeInit_p = NULL;
宣告dll handle
HINSTANCE hdll = NULL;
loadLibrary
hdll = LoadLibrary(L"DllLib.dll");if (hdll){ // Bind functions dll_Init_p = (dll_Init_def)GetProcAddress(hdll, "dll_Init"); dll_Run_p = (dll_Run_def)GetProcAddress(hdll, "dll_Run"); dll_DeInit_p = (dll_DeInit_def)GetProcAddress(hdll, "dll_DeInit");if (dll_Init_p == NULL || dll_Run_p == NULL || dll_DeInit_p == NULL) { printf("can not load func addr!!!\n"); FreeLibrary(hdll); return 1; }return 0;}
也要记得close lib
if (hdll) FreeLibrary(hdll);
呼叫lib
dll_Init_p();unsigned char* buf = (unsigned char*)malloc(sizeof(unsigned char) * 10);strcpy((char*)buf, “dllCall”);dll_Run_p(buf, 10);dll_DeInit_p();
右键属性选择起始专案为exe
执行后即可呼叫
reference - https://docs.microsoft.com/zh-tw/cpp/build/walkthrough-creating-and-using-a-dynamic-link-library-cpp?view=msvc-170
github - https://github.com/bionicqq519/DllLib