怎么用字符串的地址获取字符串本身
在VB里,用StrPtr函数取得了一个字符串的地址,通过SendMessage函数发给其他的程序,假设那个程序能够成功拿到这个地址,可是该用什么函数将它还原回字符串啊?
[解决办法]
光知道字符串地址是不行的,还应该知道字符串所占的字节长度。
给你一个完整的程序:
中英文混排有点难
Option Explicit
Private Declare Function IsTextUnicode Lib "advapi32" (lpBuffer As Any, ByVal cb As Long, lpi As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSource As Any, ByVal ByteLen As Long)
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
Private Const IS_TEXT_UNICODE_UNICODE_MASK As Long = &HF&
Private Const VER_PLATFORM_WIN32_NT As Long = 2&
'判断是否NT系统
Public Function IsWinNT() As Boolean
Dim osvi As OSVERSIONINFO
osvi.dwOSVersionInfoSize = Len(osvi)
GetVersionEx osvi
IsWinNT = (osvi.dwPlatformId = VER_PLATFORM_WIN32_NT)
End Function
'检查字符串
Public Function CheckString(msg As String) As String
If bIsWinNT Then
CheckString = StrConv(msg, vbUnicode)
Else
CheckString = msg
End If
End Function
'从起始地址获得字符串
Public Function GetStrFromPtr(lpszStr As Long, nBytes As Long) As String
ReDim ab(nBytes) As Byte
CopyMemory ab(0), ByVal lpszStr, nBytes
GetStrFromPtr = GetStrFromBuffer(StrConv(ab(), vbUnicode))
End Function
'从缓冲区获得字符串
Public Function GetStrFromBuffer(szStr As String) As String
If IsUnicodeStr(szStr) Then
szStr = StrConv(szStr, vbFromUnicode)
End If
If InStr(szStr, vbNullChar) Then
GetStrFromBuffer = Left$(szStr, InStr(szStr, vbNullChar) - 1)
Else
GetStrFromBuffer = szStr
End If
End Function
'是否Unicode字符串
Public Function IsUnicodeStr(sBuffer As String) As Boolean
Dim dwRtnFlags As Long
dwRtnFlags = IS_TEXT_UNICODE_UNICODE_MASK
IsUnicodeStr = IsTextUnicode(ByVal sBuffer, Len(sBuffer), dwRtnFlags)
End Function
Private Sub Form_Load()
Dim S As String
S = "CSDN"
Debug.Print StrConv(GetStrFromPtr(StrPtr(S), LenB(S)), vbNarrow)
S = "中文网站"
Debug.Print StrConv(GetStrFromPtr(StrPtr(S), LenB(S)), vbFromUnicode)
End Sub