现在的位置: 首页 > 综合 > 正文

讨论VB中的结构体

2013年09月03日 ⁄ 综合 ⁄ 共 2292字 ⁄ 字号 评论关闭

大笑微笑生气吐舌头吐舌头吐舌头吐舌头吐舌头吐舌头吐舌头吐舌头吐舌头吐舌头吐舌头生气微笑大笑


偷笑我爱北京天安门偷笑


偷笑天安门上太阳升偷笑


偷笑伟大领袖毛主席偷笑


偷笑指引我们向前进偷笑

偷笑大笑大笑大笑大笑大笑大笑大笑大笑大笑大笑大笑大笑大笑大笑大笑大笑偷笑

<p>VB里面的结构体是一种WORD/DWORD对齐的结构体,这一点在编程中尤其要注意,如果是纯VB编程,则结构体的各个域如何排列可以基本不用关心,<br />而如果是调用API或者是调用其他的动态链接库,则很容易出问题,原因就在于:这些动态链接库是用C/C++写的,而大部分C/C++环境里的<br />结构体是非DWORD对齐的。这就导致调用动态链接库的时候,如果传一个结构体给一个动态链接库的接口函数,可能会导致不期望的结果;</p><p>经过实验,发现VB里面结构体的DWROD规则如下:</p><p>如果结构体里面类型最大的域的字节数大于等于4个字节:<br
/>1.结构体变量的起始地址必须是4的整数倍;<br />2.结构体的每个域的起始地址必须是4的整数倍;(如果需要,通过在前一个域的末尾补占位字节来达到该目的)<br />3.结构体的总的字节数必须是4的整数倍;(不够的话,在末尾补占位字节)</p><p>如果结构体里面类型最大的域的字节数等于2个字节(就是说最大的类型才是integer):<br />1.结构体变量的起始地址必须是2的整数倍;<br />2.结构体的每个域的起始地址必须是2的整数倍;(如果需要,通过在前一个域的末尾补占位字节来达到该目的)<br
/>3.结构体的总的字节数必须是2的整数倍;(不够的话,在末尾补占位字节)</p><p>如果结构体里面类型最大的域的字节数等于1个字节(就是说最大的类型才是Byte):<br />没有DWORD对齐规则,所有的域紧凑的排列,每个域紧密连在一起;也就是说:有几个域就有几个字节;</p><p><br />实验用代码如下,通过该代码可以清楚的窥探到VB结构体的存储规则:<br />-----------------------------------------------------<br />Option Explicit</p><p>Private
Type aaa<br />&nbsp;f As Byte<br />&nbsp;g As Byte<br />&nbsp;x As Byte<br />&nbsp;y As Byte<br />&nbsp;z As Byte<br />&nbsp;a As Double<br />&nbsp;b As Integer<br />&nbsp;c As Byte<br />&nbsp;d As Byte<br />&nbsp;e As Byte<br />End Type</p><p><br />Private
Type bbb<br />&nbsp;&nbsp;&nbsp; a As Byte<br />&nbsp;&nbsp;&nbsp; b As Integer<br />&nbsp;&nbsp;&nbsp; c As Byte<br />End Type</p><p>Private Type ccc<br />&nbsp;&nbsp;&nbsp; a As Byte<br />&nbsp;&nbsp;&nbsp; b As Double<br />End Type</p><p>Private Type ddd<br
/>&nbsp;&nbsp;&nbsp; a As Byte<br />&nbsp;&nbsp;&nbsp; b As Byte<br />&nbsp;&nbsp;&nbsp; e As Byte<br />&nbsp;&nbsp;&nbsp; f As Byte<br />&nbsp;&nbsp;&nbsp; g As Byte<br />End Type</p><p><br />Private Sub Command1_Click()<br />Dim s As aaa<br />MsgBox LenB(s)<br
/>MsgBox VarPtr(s) Mod 4<br />End Sub</p><p>Private Sub Command2_Click()<br />Dim x As bbb</p><p>MsgBox LenB(x)<br />MsgBox VarPtr(x) Mod 4</p><p>End Sub</p><p>Private Sub Command3_Click()<br />Dim x As ccc<br />MsgBox LenB(x)<br />End Sub</p><p>Private Sub
Command4_Click()<br />Dim x As ddd<br />MsgBox LenB(x)<br />MsgBox VarPtr(x)<br />End Sub<br />-----------------------------------------------------</p><p>根据这个规则,会发现有时候声明同样的一个结构体,仅仅由于各个域的次序不同,就会导致结构体占用的空间大小不同的现象,<br />这也可用作一个程序优化技巧,减少程序的内存占用率;</p><p>例如:<br
/>Private Type bbb<br />&nbsp;&nbsp;&nbsp; a As Byte<br />&nbsp;&nbsp;&nbsp; b As Integer<br />&nbsp;&nbsp;&nbsp; c As Byte<br />End Type</p><p>Private Type bbb<br />&nbsp;&nbsp;&nbsp; a As Byte<br />&nbsp;&nbsp;&nbsp; c As Byte<br />&nbsp;&nbsp;&nbsp; b As
Integer<br />End Type</p><p>两种声明方式完成的目的一样,但占用的内存空间是不一样的,显然后者会更节约内存;</p>

抱歉!评论已关闭.