I'm maintaining a VB6 application that contains a function for getting collection keys from a collection, into an array. It calls the CopyMemory API. For the most part it works, with one exception. The last item in the collection is corrupt when the function exits. In most cases, a collection of strings are passed into the function and the last item contains a bunch of unrecognizable characters. However, I tracked down the problem after a collection of objects were passed in and VB would crash when accessing the final item.
Here's the code that is used. Could anyone tell me what I may be able to do differently to keep from corrupting the last item in the collection? Are there any cleanup practices that must be followed with the CopyMemory API or pointers?
Code:Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" _ (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long) Declare Function lstrlenW Lib "kernel32" _ (ByVal lpString As Any) As Long Public Type CollectionData Unk0(0 To 2) As Long Unk1 As Long ElementCount As Long Unk2 As Long PtrFirstElement As Long PtrLastElement As Long Unk3 As Long Unk4 As Long Unk5 As Long End Type Public Type CollectionElement Data As Variant Key As Long PtrPrev As Long PtrNext As Long Unk0 As Long Unk1 As Long Unk2 As Long End Type Public Function GetKeys(ByVal oCollection As Collection) As String() Dim asKeys() As String Dim lIdx As Long Dim tColl As CollectionData Dim tColElem As CollectionElement Dim sKey As String If oCollection.Count > 0 Then ReDim asKeys(0 To oCollection.Count - 1) CopyMemory tColl, ByVal ObjPtr(oCollection), LenB(tColl) tColElem.PtrNext = tColl.PtrFirstElement For lIdx = 0 To tColl.ElementCount - 1 CopyMemory tColElem, ByVal tColElem.PtrNext, LenB(tColElem) sKey = String$(lstrlenW(tColElem.Key), 0) CopyMemory ByVal StrPtr(sKey), ByVal tColElem.Key, lstrlenW(tColElem.Key) * 2 asKeys(lIdx) = sKey Next End If GetKeys = asKeys End Function




Reply With Quote