1.LoadLibrary注册DLL文件
在程序中,我们使用LoadLibrary可以加载所需的DLL文件并通过GetProcAddress函数可以注册所需要调用的DLL中的函数,这种方法在实际使用时加载DLL功能,能加快程序的装入过程并节省大量的内存空间,但存在一定的弊端,比如我们需要的函数非常多的时候,需要调用GetProcAddress进行逐一注册,这样显然不太方便。如下面的程序,需要注册的函数多达十几个:
HINSTANCE vrepDll;
vrepDll = LoadLibrary(_T(DLLPTH));
DWORD err=GetLastError();//显示错误信息
simxFinish = (func_simxFinish)GetProcAddress(vrepDll, "simxFinish");
simxStart = (func_simxStart)GetProcAddress(vrepDll, "simxStart");
simxStartSimulation = (func_simxStartSimulation)GetProcAddress(vrepDll, "simxStartSimulation");
simxSetJointTargetPosition = (func_simxSetJointTargetPosition)GetProcAddress(vrepDll, "simxSetJointTargetPosition");
simxSetJointTargetVelocity = (func_simxSetJointTargetVelocity)GetProcAddress(vrepDll, "simxSetJointTargetVelocity");
simxSetJointPosition = (func_simxSetJointPosition)GetProcAddress(vrepDll, "simxSetJointPosition");
simxGetObjectHandle = (func_simxGetObjectHandle)GetProcAddress(vrepDll, "simxGetObjectHandle");
simxStopSimulation = (func_simxStopSimulation)GetProcAddress(vrepDll, "simxStopSimulation");
simxGetObjectPosition= (func_simxGetObjectPosition)GetProcAddress(vrepDll, "simxGetObjectPosition");
simxGetObjectOrientation= (func_simxGetObjectOrientation)GetProcAddress(vrepDll, "simxGetObjectOrientation");
2.装入时动态链接替换函数注册
由于GetProcAddress逐一注册函数的不方便性,因此考虑装入时注册的方法进行注册。如我们在程序中需要使用remoteApi.dll对象中的若干个函数,此时我们可以将dll文件生成lib文件然后再进行调用。
2.1windows下dll生成lib文件
找到vs工具下的 Developer Command Prompt for VS 2019,如下图:
输入dll文件所在路径,如remoteApi.dll文件在G:\proj\testDLL
生成def文件,输入dumpbin /exports remoteApi.dll> remoteApi.def
修改def文件为标准文件(只保留函数名),并在头部加上如下语句(注意和dll文件名称一致):
EXPORTS
接下来生成lib文件即可,注意X86还是X64:lib /def:remoteApi.def /machine:x64 /out:remoteApi.lib
最后,将生成的remoteApi.lib复制一份到VS生成的.exe目录下:
最后,将dll所在位置和lib所在位置在程序中进行链入,同时加入相关头文件即可