How to Allocate Global Memory from Within the LCK

ID: Q120467

The information in this article applies to:

SUMMARY

It may be necessary to allocate global memory within an FLL. To do this, use the following Windows API functions: GlobalAlloc(), GlobalLock(), GlobalUnlock(), and GlobalFree().

MORE INFORMATION

To use Windows global memory, follow these steps:

1. Use the GlobalAlloc() Windows API function to request the memory. The

   global heap is limited only by the systems memory, so you can request
   any amount of memory. GlobalAlloc() allocates memory in multiples of 32.
   For example, if you request 50 bytes, GlobalAlloc() will allocate 64
   bytes.

2. To use the allocated memory, lock the memory block with GlobalLock(). If
   GlobalLock() is successful, it returns a far pointer to the starting
   point of the allocated memory block. This pointer can be used in
   conjunction with the LCK to write to the specified location.

3. When you no longer need the global memory block, unlock and release it
   by using GlobalUnlock() and GlobalFree().

Example Code

The following program passes a string to the FLL and allocates enough global memory for the string.

Fox Code:

   SET LIBRARY TO MEMALLOC.FLL
   =MEMALLOC('THIS IS A TEST')

C Code:

   #include <windows.h>
   #include <pro_ext.h>

   static      HANDLE      hMem;
   char      FAR     *pmem;
   DWORD        before;
   LPSTR     lpstr;

   void PutLong(long v,int width)
   {
   Value val;
   val.ev_long  = v;
   val.ev_width = width;
   val.ev_type  = 'I';
   _PutValue(&val);
   }

   void MemAlloc(ParamBlk FAR *parm)
   {
   before = GetFreeSpace(0);
   _PutStr("Total memory avaiable in the Global Heap before memory
      allocation = "); PutLong(before,10);
   if(hMem = GlobalAlloc(GMEM_MOVEABLE, parm->p[0].val.ev_length))
   {
      _PutStr("\nAmount of memory allocated =");
      PutLong((before-GetFreeSpace(0)),3);
      lpstr=GlobalLock(hMem);
      lstrcpy(lpstr,(LPSTR)_HandToPtr(parm->p[0].val.ev_handle));
      GlobalUnlock(hMem);
      GlobalFree(hMem);
   }
   _PutStr("\nAmount of memory after hMem is is release = ");
   PutLong(GetFreeSpace(0),10);
   }

   FoxInfo myFoxInfo[]={
      {"MEMALLOC",(FPFI)MemAlloc,1,"C"},
   };

   FoxTable _FoxTable={
      (FoxTable FAR*)0, sizeof(myFoxInfo) / sizeof(FoxInfo), myFoxInfo
   };

Additional reference words: FoxWin 2.50 2.50a 2.50b 2.60 2.60a LCK API KBCategory: kbprg kbcode KBSubcategory: FxtoolLck

Last Reviewed: August 28, 1995