Marshal.SizeOf()在尝试计算MyClass类型对象的长度时会抛出异常。
这是班级:
<StructLayout(LayoutKind.Sequential, Pack:=1)>
Public Class MyClass
Public ReadOnly UniqueId As Long
<MarshalAs(UnmanagedType.AnsiBStr, SizeConst:=60, SizeParamIndex:=0)>
Public ReadOnly Name As String
End Class
此代码将失败:
Dim MyObject = New MyClass()
Dim size = Marshal.SizeOf(MyObject) 'will throw exception here. Why?
它将抛出异常“无法计算有意义的大小或偏移量”
我怎样才能获得MyObject的长度呢?
答案 0 :(得分:0)
我相信UnmanagedType.AnsiBStr
只能用于方法签名的参数(传递值)。
对BSTR的引用是指向长度前缀字符数组的指针。因此,它将是一个大小为4或8字节的.Net Intptr,具体取决于进程位数(x32或x64)。如果您需要ANSI字符,请将其定义为StructLayout
声明的一部分,并将字符串标记为UnmanagedType.BStr
<StructLayout(LayoutKind.Sequential, Pack:=1, CharSet:=CharSet.Ansi)>
Public Class [MyClass]
Public ReadOnly UniqueId As Long
<MarshalAs(UnmanagedType.BStr)>
Public ReadOnly Name As String
End Class
推荐阅读:
答案 1 :(得分:-1)
class Program
{
static void Main(string[] args)
{
TestingData p = new TestingData();
Console.WriteLine("Number of bytes : {0}", Marshal.SizeOf(p));
}
}
public struct TestingData
{
public string a;
}
希望它会有所帮助。有关更多信息,请访问Marshal Documentation