Out of String Space in Visual Basic 6

后端 未结 6 1506
误落风尘
误落风尘 2020-12-16 18:03

We are getting an error in a VB6 application that sends data back and forth over TCP sockets. We get a runtime error \"out of string space\". Has anyone seen this or have

6条回答
  •  [愿得一人]
    2020-12-16 18:33

    As others have pointed out, every string concatenation in VB will allocate a new string and then copy the data over and then de-allocate the original once it can. In a loop this can cause issues.

    To work around this you can create a simple StringBuilder class like this one:

    Option Explicit
    
    Private data As String
    Private allocLen As Long
    Private currentPos As Long
    
    Public Function Text() As String
      Text = Left(data, currentPos)
    End Function
    
    Public Function Length() As Long
      Length = currentPos
    End Function
    
    Public Sub Add(s As String)
    
      Dim newLen As Long
      newLen = Len(s)
      If ((currentPos + newLen) > allocLen) Then
        data = data & Space((currentPos + newLen))
        allocLen = Len(data)
      End If
    
      Mid(data, currentPos + 1, newLen) = s
      currentPos = currentPos + newLen
    
    End Sub
    
    Private Sub Class_Initialize()
      data = Space(10240)
      allocLen = Len(data)
      currentPos = 1
    End Sub
    

    This class will minimize the number of string allocations by forcing the string to be built with spaces in it and then overwriting the spaces as needed. It re-allocates to roughly double its size when it finds that it does not have enough space pre-initialized. The Text method will return the portion of the string that is actually used.

提交回复
热议问题