Dim strSrc As String * 20
Dim strDst As String * 20
Dim buffer() As Byte
ReDim buffer(LenB(strSrc))
strSrc = "HelloWorld"
Print "生成源目标字符串:" & strSrc
Print "正在拷贝到缓冲区..."
CopyMemory buffer(0), strSrc, LenB(strSrc)
Print "拷贝到缓冲区完成, 共" & LenB(strSrc) & "个字节"
Print "正在拷贝到目标字符串"
CopyMemory strDst, buffer(0), LenB(strDst)
Print "拷贝到目标完成. 目标字符串:" & strDst
Print "完成"
CopyMemory strDst, strSrc, Len(strSrc)
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Sub Command1_Click()
Dim strSrc As String * 20
Dim strDst As String * 20
Dim buff() As Byte
Dim buffer() As Byte
ReDim buffer(LenB(strSrc) - 1)
strSrc = "HelloWorld"
Print "生成源目标字符串:" & strSrc
Print "正在拷贝到缓冲区..."
buff = strSrc
CopyMemory buffer(0), buff(0), LenB(strSrc)
Print "拷贝到缓冲区完成, 共" & LenB(strSrc) & "个字节"
Print "正在拷贝到目标字符串"
Dim buff1() As Byte
ReDim buff1(LenB(strSrc) - 1)
CopyMemory buff1(0), buffer(0), LenB(strDst)
strDst = buff1
Print "拷贝到目标完成. 目标字符串:" & strDst
Print "完成"
End Sub
1. lenB的使用,如同" lxcc(虫子|需要点勇气和信心)"讲解的,如果字符串中有汉字或全角字符,其结果肯定有错。
2. 参数传递方式存在问题。在CopyMemort中不使用定长字符串是正确的,否则很麻烦。我做过两个函数,通常是这么用的, 现在给你:Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
'**********************************************
' 把字符串存入字节数组, 返回字符串的长度
'**********************************************
Private Function SaveStringToByteArry(strString As String, BytArray() As Byte) As Long
Dim lngStrLen As Long
'** 获取字符串的长度(字节)
lngStrLen = LenB(StrConv(strString, vbFromUnicode))
'** 分配数组空间
ReDim BytArray(lngStrLen - 1) '** 将字符串地址中的内容拷贝到数组
CopyMemory BytArray(0), ByVal strString, lngStrLen
SaveStringToByteArry = lngStrLen
End Function'**********************************
' 字节数组中的数据连接成字符串
'**********************************
Private Function CreateStringFromByte(ByteArray() As Byte, ByteLength As Long) As String
Dim StringData As String
'** 分配字符串空间
StringData = Space(ByteLength) '** 复制字符数组地址内容到字符串地址
CopyMemory ByVal StringData, ByteArray(0), ByteLength
'** 返回字符串
CreateStringFromByte = StringData
End Function