Visual Basic 6 中的字符串空间不足 [英] Out of String Space in Visual Basic 6

查看:11
本文介绍了Visual Basic 6 中的字符串空间不足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在通过 TCP 套接字来回发送数据的 VB6 应用程序中遇到错误.我们得到一个运行时错误字符串空间不足".有没有人看到这个或有任何想法为什么会发生这种情况?似乎我们正在达到一些 VB6 阈值,因此任何其他想法也会有所帮助.

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 any thoughts on why this would happen? It seems like we are hitting some VB6 threshhold so any other thoughts would be helpful as well.

推荐答案

正如其他人所指出的,VB 中的每个字符串连接都会分配一个新字符串,然后将数据复制过来,然后尽可能取消分配原始字符串.在循环中,这可能会导致问题.

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.

要解决这个问题,您可以创建一个像这样的简单 StringBuilder 类:

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

这个类将通过强制在字符串中包含空格然后根据需要覆盖空格来最小化字符串分配的数量.当它发现它没有足够的预初始化空间时,它会重新分配大约两倍的大小.Text 方法将返回实际使用的字符串部分.

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.

这篇关于Visual Basic 6 中的字符串空间不足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆