Private
Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory"
(Destination As Any, Source As Any, ByVal Length As
Long)
'不要直接对sString赋值(可以用MID语句),将其设为公有仅为提高效率。 Public sString As
String 'BSTR描述符指针
Private pStr As Long 'BSTR地址 Private nMaxLen
As Long 'BSTR最大字节数
'让本字串指向特定地址 Public Sub
Attach(Addr As Long, Optional nLen As Long) pStr =
Addr '修改BSTR描述符指针,使其指向Addr CopyMemory ByVal VarPtr(sString), Addr,
4
If IsMissing(nLen) Then Exit Sub '设定最大字串字节数 nMaxLen =
nLen
End Sub
'还原本字串原BSTR描述符 Public Sub
Detach() CopyMemory ByVal VarPtr(sString), 0&, 4 End
Sub
'让本字串指向源字串 Public Sub AttachStr(sStr As String) Attach
StrPtr(sStr), LenB(sStr) End Sub
'data为缺省属性 Public
Property Let data(sVal As String) Dim c As Long c =
LenB(sVal) '超过最大字串数,抛出错误。 If c > nMaxLen Then Err.Raise
vbObjectError + 3000, "CString::Let Data", "溢出" '写字串长度 CopyMemory
ByVal (pStr - 4), c, 4 '写字串 Mid(sString, 1) = sVal End
Property
'可以通过公有变量sString来读字串,效率更高 Public Property Get data() As
String data = sString End Property