How do I add call a function in a dll in another project
I have a console C++ app and I want to call a function add() in another dll C++ project. Whats the way to 开发者_如何学Cdo it?
Use LoadLibrary and then GetProcAddress to get the function pointer.
DLL files are accessed either by their corresponding .LIB
files, included in your project along with their header #include "MyUtils.h"
. That's called static linking, and it's all done at compile time as far as you are concerned, and you call the DLL's functions as if they were defined in your own application.
Another method is dynamic linking, where you actually load the DLL and obtain the function's address before making the call. An example of this approach is as follows:
// Declare the 'type' of the function, for easier use.
typedef BOOL (* t_MyFunc)(DWORD dwParam1, int nParam2);
// Declare a pointer to the function. Via this pointer we'll make the call.
t_MyFunc MyFunc = 0;
BOOL bResult = FALSE;
// Load the DLL.
HMODULE hModule = LoadLibrary("MyDLL.dll");
assert(hModule);
// Obtain the function's address.
MyFunc = (t_MyFunc)GetProcAddress(hModule, "MyDLL.dll");
assert(MyFunc);
// Use the function.
bResult = MyFunc(0xFF00, 2);
// No need in MyDll.dll or MyFunc anymore. Free the resources.
FreeLibrary(hModule);
There are several more consideration to take into account, depending on whether you compiled the DLL or using some else's, such as how the function(s) were exported. But this should get you started.
精彩评论