|
-
Jul 8th, 2009, 10:02 AM
#5
Junior Member
Re: How to memory management in VB 6
You could always make a set of memory allocate/reallocate/free functions, using kernel32 like so;
vb Code:
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef destination As Any, ByRef Source As Any, ByVal numbytes As Long)
Public Declare Sub ZeroMemory Lib "kernel32" Alias "RtlZeroMemory" (ByRef destination As Any, ByVal numbytes As Long)
Public Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, ByVal dwBytes As Long) As Long
Public Declare Function GlobalFree Lib "kernel32" (ByVal hMem As Long) As Long
Public Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) As Long
Public Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) As Long
Public Function malloc(ByVal dwSize As Long) As Long
Dim lngHandle As Long
lngHandle = GlobalAlloc(0, dwSize + 4)
malloc = GlobalLock(lngHandle) + 4
Call CopyMemory(ByVal malloc - 4, lngHandle, 4)
End Function
Public Sub free(ByVal dwPtr As Long)
Dim lngHandle As Long
Call CopyMemory(lngHandle, ByVal dwPtr - 4, 4)
Call GlobalUnlock(lngHandle)
Call GlobalFree(lngHandle)
End Sub
I've persionaly use'd this function alot in the past -- it can really speed things up with dealing with large data blocks.
One thing that springs to mind, is reading data from a 10MB file.
allocating a 10mb byte array in vb, will be rather slow, since vb nulls the memory before use. 200ms springs to mind. If said memory does not need to be null'ed, you can allocate 10mb of memory pretty much isntantly.
In the example above, I allocate an extra 4 bytes, to store the handle to said memory, in the 1st 4 bytes, then return an address just past it.
You may also want to store other infomation, like size of memory, etc etc.
Hope this helps
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|