lpwsz = StrPtr(sBSTR)
'''' Copy the array
CopyMemory b(1), ByVal lpwsz, cBytes + 2
'''' Point lpsz to new array
lpwsz = VarPtr(b(1))
'''' Return byte count
BSTRtoLPWSTR = cBytes
End Function
函数接收一个BSTR和一个动态Byte数组,以及一个长整型变量并将BSTR转换为一个LPWSTR,保存在Byte数组中。数组的首地址赋予lpwsz。它的返回值是数组的长度。下面是一个调用该函数的例子。
Dim b() As Byte
Dim lpsz As Long, lng As Long
lng = BSTRToLPWSTR("here", b, lpsz)
如果你仔细看了BSTR和C语言类型的LPSTR和LPWSTR这几个部分的话,你会发现,其实上面三句代码与下面代码等价。
lpsz = StrPtr(sBSTR)
从BSTR到LPSTR
将BSTR转换到LPSTR与LPWSTR类似,只须注意Unicode格式到ANSI格式的转换就行了。函数如下:
Function BSTRtoLPSTR(sBSTR As String, b() As Byte, lpsz As Long) As Long
'''' Input: a nonempty BSTR string
'''' Input: **undimensioned** byte array b()
'''' Output: Fills byte array b() with ANSI char string
'''' Output: Fills lpsz with a pointer to b() array
'''' Returns byte count, not including terminating null
'''' Original BSTR is not affected
Dim cBytes As Long
Dim sABSTR As String
cBytes = LenB(sBSTR)
'''' ReDim array, with space for terminating null
ReDim b(1 To cBytes + 2) As Byte
'''' Convert to ANSI
sABSTR = StrConv(sBSTR, vbFromUnicode)
'''' Point to BSTR char array
lpsz = StrPtr(sABSTR)
'''' Copy the array
CopyMemory b(1), ByVal lpsz, cBytes + 2
'''' Point lpsz to new array
lpsz = VarPtr(b(1))
'''' Return byte count
BSTRtoLPSTR = cBytes
End Function
从LPWSTR到BSTR
如果从一个API函数返回是LPWSTR(就是说一个指向空字节结尾的Unicode格式的字符串指针),Visual Basic可以轻松地将它转换为BSTR。
以下是一个小小的工具函数:
Function LPWSTRtoBSTR(ByVal lpwsz As Long) As String
'''' Input: a valid LPWSTR pointer lpwsz
'''' Return: a sBSTR with the same character array
Dim cChars As Long
'''' Get number of characters in lpwsz
cChars = lstrlenW(lpwsz)’该函数为strlen的C语言版本
'''' Initialize string
LPWSTRtoBSTR = String$(cChars, 0)
'''' Copy string
上一页 [1] [2] [3] [4] [5] 下一页 |