By Andrew Tucker
Welcome to the first installment of the Windows CE Power Magazine Programming Power column! Each month we'll address tough issues about writing software for Windows CE and provide solutions that usually include a code snippet or two.
This month, we've selected issues that are common stumbling blocks. But what will really make this column work is if we answer questions from those of you fighting daily battles in the trenches. Want to know how to workaround an API that's not available on Windows CE? Need help determining if your code will work on both a Palm-sized PC and a H/PC Pro? Send us email at email@example.com, including code where appropriate, and we'll try our hardest to find a resolution for you.
Most of the topics we'll cover are for those of you using the Visual C++ Toolkit for Windows CE, but we'll address occasional questions about Visual Basic for Windows CE and other development tools as well. Without further ado, let's jump into this month's questions.
How come calling CoFreeUnusedLibraries doesn't seem to release any of my DLLs, even though there are no outstanding COM objects?
Using memory efficiently is always a good idea for any software system, but it's paramount for most Windows CE applications. Since embedded devices don't have the seemingly endless RAM and hard drive space of desktop systems, a memory hogging application can quickly have a dramatic affect on system performance.
The designers of COM had this issue in mind when they came up with the CoFreeUnusedLibraries API. Calling this function occasionally, usually in a message loop or when the system is idle, will release any DLLs that don't have any COM objects currently dependent on them. A DLL indicates a willingness to be unloaded by returning S_OK from its exported DllCanUnloadNow function. On Windows CE however, a return value of S_OK doesn't result in the DLL being freed up immediately.
Once a DLL has indicated that it's able to be unloaded, CoFreeUnusedLibraries just captures the current system time. On subsequent calls to CoFreeUnusedLibraries if DllCanUnloadNow still returns S_OK and a specified time period has elapsed, then the DLL is actually freed. If during the time period DllCanUnloadNow returns S_FALSE, the clock is reset and the whole process starts over.
The default time period that CoFreeUnusedLibraries waits is ten minutes -- much longer than the patience of most developers that are trying to test their DllCanUnloadNow implementation.