visual studio dll lib 建立与呼叫

建立dll专案
http://img2.58codes.com/2024/Vr6frEt.png

新增档案
http://img2.58codes.com/2024/8dzOeuN.png

设定不使用先行标题档
http://img2.58codes.com/2024/ymIElaE.png

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档
http://img2.58codes.com/2024/a1itMQZ.png

建立空白专案来呼叫dll
http://img2.58codes.com/2024/XFxZxwN.png

新增档案
http://img2.58codes.com/2024/qeSYer7.png

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
http://img2.58codes.com/2024/D3FhWvX.png

执行后即可呼叫
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


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章