|
-
Jul 20th, 2008, 08:59 PM
#1
VB6 String to Integer Array
This is a simple demonstration that hacks an integer array to point into string data. The method shown here does not copy the entire data, it just changes the required information so that you can access the data.
It is not safe to use ReDim or ReDim Preserve. (You may crash.)
This lets you have a very fast access to the actual character code values. The first character is at position 2 (positions 0 and 1 contain the string length information and should not be changed). UBound of the integer array must remain zero, it is the terminating null character of a string. All other values can be modified freely.
As this is pretty much hacking the memory, you should also restore the original state once you're done, for this reason there is a reversing sub for the job.
Code:
Option Explicit
Private Declare Sub GetMem4 Lib "msvbvm60" (Destination As Any, Value As Any)
Private Declare Sub PutMem4 Lib "msvbvm60" (Destination As Any, Value As Any)
' reverses the effects of StringToIntegerArray
Public Sub IntegerArrayToString(ByRef IntegerArray() As Integer, ByRef StringToFill As String)
Dim lngPtr As Long, lngArrayPtr As Long
' get the array data pointer
lngArrayPtr = (Not Not IntegerArray) + 12
If lngArrayPtr > 12 Then
' get it
GetMem4 ByVal lngArrayPtr, lngPtr
' overwrite it with pointer to string data
PutMem4 ByVal lngArrayPtr, ByVal StrPtr(StringToFill) - 4
' change number of elements
PutMem4 ByVal lngArrayPtr + 4, ByVal Len(StringToFill) + 3
' now as for the string...
PutMem4 ByVal VarPtr(StringToFill), ByVal lngPtr + 4
' remove the integer array
Erase IntegerArray
End If
End Sub
' makes string an integer array
Public Sub StringToIntegerArray(ByRef StringToNull As String, ByRef IntegerArray() As Integer)
Dim lngPtr As Long, lngArrayPtr As Long
' erase old array, create empty data for an empty string
ReDim IntegerArray(2)
' get the array data pointer
lngArrayPtr = (Not Not IntegerArray) + 12
' get it
GetMem4 ByVal lngArrayPtr, lngPtr
' overwrite it with pointer to string data
PutMem4 ByVal lngArrayPtr, ByVal StrPtr(StringToNull) - 4
' change number of elements
PutMem4 ByVal lngArrayPtr + 4, ByVal Len(StringToNull) + 3
' now as for the string...
PutMem4 ByVal VarPtr(StringToNull), ByVal lngPtr + 4
End Sub
Private Sub Form_Load()
Dim intTest() As Integer, strTest As String
strTest = "ABC"
StringToIntegerArray strTest, intTest
MsgBox intTest(2) & vbNewLine & intTest(3) & vbNewLine & intTest(4)
IntegerArrayToString intTest, strTest
MsgBox strTest
End Sub
I may do some futher adjustments to this later on, now I just had to start closing all the applications out of the way (I had like 7 instances of VB6 running, about time to do desktop cleanup).
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
|