VB.net将结构体定长字符串转字节数组时怎么丢了一位呢?? 50
ImportsSystem.Runtime.InteropServicesModuleModule1<StructLayout(LayoutKind.Sequential...
Imports System.Runtime.InteropServices
Module Module1
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode, pack:=1)> Public Structure a
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=3)> Public s As String
End Structure
Public Function StructureToByte(ByVal obj As Object) As Byte()
Dim size As Integer = Marshal.SizeOf(obj)
Dim bytes(size - 1) As Byte
Dim ptr As IntPtr = Marshal.AllocHGlobal(size)
Marshal.StructureToPtr(obj, ptr, False)
Marshal.Copy(ptr, bytes, 0, size)
Marshal.FreeHGlobal(ptr)
Return bytes
End Function
主程序中
Dim tt As New a
t.s="aaa"
Dim bytess() = StructureToByte(tt)
bytess怎么就只有两个字符啊?少了第三个字符
求解答
然后调用bytes 展开
Module Module1
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode, pack:=1)> Public Structure a
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=3)> Public s As String
End Structure
Public Function StructureToByte(ByVal obj As Object) As Byte()
Dim size As Integer = Marshal.SizeOf(obj)
Dim bytes(size - 1) As Byte
Dim ptr As IntPtr = Marshal.AllocHGlobal(size)
Marshal.StructureToPtr(obj, ptr, False)
Marshal.Copy(ptr, bytes, 0, size)
Marshal.FreeHGlobal(ptr)
Return bytes
End Function
主程序中
Dim tt As New a
t.s="aaa"
Dim bytess() = StructureToByte(tt)
bytess怎么就只有两个字符啊?少了第三个字符
求解答
然后调用bytes 展开
1个回答
展开全部
你搞错了一点:Unicode字符规定,每个字符占用两个字节,包括英文和数字,所以你只需将:
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=3)> Public s As String
改成:
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=6)> Public s As String
即可!
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=3)> Public s As String
改成:
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=6)> Public s As String
即可!
追问
sizeconst=6 那样我这个结构体的长度就不是6个字节了 而是12个字节。我就是想要一个结构体占用6个字节 有三个unicode码表示{[97] [0] [97] [0] [97] [0]}表示“aaa”。应该怎么写?你可以运行一下我的代码。是6个字节,就是最后两个字节为[0] [0].
追答
最后两个0 0 ,代表字符串结束,你可以改成Ansi不用Unicode:
Public Structure a
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询