I am searching for a function to get time in milliseconds on a windows machine. Essentially, I want to call this WinAPI function GetTickCount(), but I'm stuck on "use LoadLibrary(...) n call GetTickCount() function" part..
I searched every forum n googled it but everywhere people have used incomplete codes that don't compile..Can anyone write a short sample program to load kernel32.dll and call GetTickCount() to display the time in milliseconds?
Please write code that compiles!
[kernel32.dll] is loaded in every process, because it provides the
ExitProcess
function…All you have to do is include
<windows.h>
and callGetTickCount
.Cheers & hth.,
The very first thing you should do is declare a function pointer type that's compatible with the exported function. Getting this right is critical and the greatest odds for running into trouble. Look carefully at the function declaration to arrive at this:
Next, use LoadLibrary and GetProcessAddress to obtain the function pointer value. You always have to cast the return value of GPA to the function pointer type. Like this:
Failure modes here are the path to the DLL. I didn't have to specify one because kernel32.dll is stored in c:\windows\system32, a directory that's always in the search path. That's generally not the case for your own DLL. Only storing it in the same directory as your main EXE allows you to specify just the DLL file name instead of the full path. Review the docs for SetDllDirectory() for background info.
And the name of the exported function. Again it was easy here, the Windows API functions are exported with undecorated names. That's generally not the case for your own DLL, exports can be exported with a leading underscore, a "@nn" postfix or a mangled name if you didn't declare the function with extern "C" and used the C++ compiler. To see the real name use Dumpbin.exe /exports on your DLL. Also note that GetProcAddress uses a const char*, unlike the rest of the Windows API that uses Unicode strings. No L prefix on the string literal.
Then you call it, that's easy:
If you got the function pointer type declaration wrong then you may crash your program with an AV, get bizarre function results or an imbalanced stack.
You can't load
kernel32.dll
, it's already loaded into every process. AndGetTickCount
exists on every version of Windows, so you don't needGetProcAddress
to see if it exists. All you need is:A dynamic load example (since
winmm.dll
is not preloaded):I've successfully compiled and run this example using Visual Studio 2010 command prompt, no special compiler or linker options are needed.
You don't have to. Kernel32.dll is loaded into every x86 process on Windows. You only have to include the header to make it work- the compiler will load it for you.