Share via


How to: Manage Memory

You can allocate and manage memory using the Visual FoxPro API.

Note

The techniques described apply to both ActiveX controls and FLL libraries.

To allocate and use memory

  1. Allocate a handle with _AllocHand( ).

  2. Lock the handle with _HLock( ).

  3. Convert the handle into a pointer with _HandToPtr( ).

  4. Reference the memory by using the pointer.

  5. Unlock the handle with _HUnLock( ).

    Note

    To avoid memo file corruption, don't write to a memo file before calling _AllocMemo( ).

In order to address the allocated memory, your API routines must convert the handle to a pointer by calling the _HandToPtr( ) routine. Even if the Visual FoxPro memory manager needs to reorganize memory to obtain more contiguous memory for subsequent memory requests, the handle remains the same. Routines that grow, shrink, free, and lock memory allocations are also provided.

When you're creating external routines, try to minimize memory use. If you create an external routine that dynamically allocates memory, try to use the least amount of memory possible. Be especially careful about locking large memory allocations for long periods of time. Remember to unlock memory handles with _HUnLock( ) when they no longer need to be locked, because the performance of Visual FoxPro can be adversely affected by locked memory handles.

Warning

Excessive use of dynamic memory deprives Visual FoxPro of memory for buffers, windows, menus, and so on, and degrades performance, because the memory given to fill API requests is managed by the Visual FoxPro memory manager. Allocating large handles and retaining them could cause Visual FoxPro to run out of memory and terminate abnormally. The Visual FoxPro environment has no memory protection. The external API routine cannot provide all the validation that's inherent in a standard Visual FoxPro program. If you corrupt memory, you receive messages such as "Transgressed handle," "Internal consistency error," and "Transgressed node during compaction."

The following function from an FLL library illustrates memory allocation. The example uses _RetDateStr( ) to return a Visual FoxPro Date type (assuming that the Character parameter is a proper date):

#include <Pro_ext.h>

void dates(ParamBlk  *parm)
{
   MHANDLE mh;
   char *instring;

   if ((mh = _AllocHand(parm->p[0].val.ev_length + 1)) == 0) {
      _Error(182); // "Insufficient memory"
   }
   _HLock(parm->p[0].val.ev_handle);
   instring = _HandToPtr(parm->p[0].val.ev_handle);
   instring[parm->p[0].val.ev_length] = '\0';
   _RetDateStr(instring);
   _HUnLock(parm->p[0].val.ev_handle);
}
FoxInfo myFoxInfo[] = {
   {"DATES", (FPFI) dates, 1, "C"}
};
FoxTable _FoxTable = {
   (FoxTable *) 0, sizeof(myFoxInfo)/sizeof(FoxInfo), myFoxInfo
};

See Also

Concepts

Memory Management Using the Visual FoxPro API

Other Resources

Accessing the Visual FoxPro API