Memory Management Functions
Let’s review some of the common Palm OS SDK functions for managing memory.
To allocate memory, use MemHandleNew as
follows:
typedef struct GlobalVarsType
{
Int16 nOpenCount; // library open count
Int16 nContextCount; // number of contexts using this library
//Other library global variables
}GlobalVarsType;
UInt32 nMemSize = sizeof(GlobalVarsType);
//Allocate global memory
MemHandle gHandle = MemHandleNew(nMemSize);To lock a chunk of memory for read/write access, use the following sequence.
MemPtr gLockPtr; gLockPtr = MemHandleLock(gHandle); //read from or write to global memory MemHandleUnlock(gHandle);
Alternatively, since MemHandleLock returns
a
MemPtr, you may use the following
MemHandleLock/MemPtrUnlock
pair:
MemPtr gLockPtr; gLockPtr = MemHandleLock(gHandle); //read from or write to global memory MemPtrUnlock(gLockPtr);
To set the owner ID of memory so it belongs to the OS, you must first lock the memory chunk, set the owner ID, and then unlock the memory chunk. You typically set the owner ID immediately after creating the memory:
MemHandle gHandle = MemHandleNew(nMemSize); MemPtr gLockPtr = MemHandleLock(gHandle); //Set the owner to the OS, so it is not freed automatically. MemPtrSetOwner(gLockPtr, 0); MemPtrUnlock(gLockPtr);
When your library is done with its global memory—which is
typically when the last application unloads it from memory—the
library
should
free its memory using MemHandleFree, as follows:
//Our library is being closed by ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access