【问题标题】:VB.Net Len(structure) = invalid type in structureVB.Net Len(结构)=结构中的无效类型
【发布时间】:2013-06-09 12:31:43
【问题描述】:

当我尝试读取我的结构的内存大小时,我得到了异常:

“具有“UInt16”类型字段“cbSize”的结构的文件 I/O 无效。”

我的结构:

 <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi, Pack:=1)>
 Public Structure MyStructure
    Public V1 As UInt16         

    <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=30)> _
    Public V2 As String 
    Public V3 As Integer             
    <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=256)> _
    Public V4 As String    
    Public V5 As Byte         
    Public V6 As Byte            
    Public V7 As UInt16        
    Public V8 As UInt16         
    Public V9 As UInt16       


    Public V10 As Integer            
    Public V11 As Integer      
    <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=8)> _
    Public V12 As String  
 End Structure

我写了一个函数来计算每个 Len(Vxx) 的值。此功能有效,但我得到了错误的值...

 size = Len(V1) + Len(V2) + Len(V3) ....

当我将值 Type 更改为 Int16 时,Len(structure) 没有问题。

现在我的问题是: 为什么它不适用于 UInt16?

有什么方法可以让我使用 UInt16 并从 Len() 获得正确的值?

感谢您的建议。

【问题讨论】:

    标签: vb.net variables types structure memory-size


    【解决方案1】:

    像这样使用Marshal.SizeOf()

        Dim ms As New MyStructure
        ' ... populate "ms" ...
        Dim sz As Integer = Marshal.SizeOf(ms)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 2020-04-03
      • 2021-12-23
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 2020-12-30
      相关资源
      最近更新 更多