请问, 为何Integer在内存中占用4字节? CopyMemory数据出错

Herro 2004-01-16 09:01:27
很奇怪, 百思不得其解.
代码如下
Public Type BITMAPFILEHEADER
bfType As Integer 'must be 19778 = "BM"
bfSize As Long 'size of file in bytes LOF(%bf)
bfReserved1 As Integer 'Reserved must be set to zero
bfReserved2 As Integer 'Reserved must be set to zero
bfOffBits As Long 'the begining of the actual bmp data
End Type

Private m_bfh As BITMAPFILEHEADER
CopyMemory m_bfh, Stream(0), Len(m_bfh) 'stream是图像的数据流

结果m_bfh.bfReserved2的数据是bfOffBits的.

我看了下m_bfh的内存, 发现如果用Get #1,,m_bfh得到的数据是
42 4D 00 00 36 5A 09 00 00 00 00 00 36 00 00 00 ; BM..6Z......6...
占用了16位也! 当然len得出来是14.
而且m_bfh.bfSize的指针也确实指向36 5A

而从stream CopyMemory 进去的是
42 4D 36 5A 09 00 00 00 00 00 36 00 00 00 ; BM6Z......6...
这才是正确的源图像文件数据啊...

好像只有这个自定义类型有这种问题, 请问发生的原因和解决方法?
先谢了.
...全文
189 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
rainstormmaster 2004-01-16
  • 打赏
  • 举报
回复
数据对齐的原因,为了处理更快,会把自定义类型大小对齐到 4的整数倍


另外:
//CopyMemory m_bfh, Stream(0), Len(m_bfh) 'stream是图像的数据流
图像的数据流是什么意思?

既然,你定义了:
Private m_bfh As BITMAPFILEHEADER

那么Stream中包含文件头信息吗,Stream又是如何获得的?请详细说明一下。
Herro 2004-01-16
  • 打赏
  • 举报
回复
学到知识了..
大感激!
只好一个个copy了..
o光o 2004-01-16
  • 打赏
  • 举报
回复
这可以试试 加一个 变量或少一个变量
lk_cool 2004-01-16
  • 打赏
  • 举报
回复
同上
o光o 2004-01-16
  • 打赏
  • 举报
回复
这是因为 数据对齐的原因,为了处理更快,会把自定类型大小对齐到 4的整数倍
Herro 2004-01-16
  • 打赏
  • 举报
回复
我把试验代码帖出来, 复制一下运行看看...很奇怪....

Option Explicit

Private Type BITMAPFILEHEADER
bfType As Integer 'must be 19778 = "BM"
bfSize As Long 'size of file in bytes LOF(%bf)
bfReserved1 As Integer 'Reserved must be set to zero
bfReserved2 As Integer 'Reserved must be set to zero
bfOffBits As Long 'the space between this struct and the begining of the actual bmp data
End Type

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpDst As Any, lpSrc As Any, ByVal Length As Long)

Dim bmfh As BITMAPFILEHEADER

Private Sub Form_Load()
Dim A(13) As Byte

A(0) = 0
A(1) = 1

A(2) = 0
A(3) = 0
A(4) = 0
A(5) = 1

A(6) = 0
A(7) = 1

A(8) = 0
A(9) = 1

A(10) = 0
A(11) = 0
A(12) = 0
A(13) = 1

CopyMemory bmfh, A(0), Len(bmfh)
Debug.Print Hex(VarPtr(bmfh)) '获得指针

Debug.Print bmfh.bfType
Debug.Print bmfh.bfSize
Debug.Print bmfh.bfReserved1
Debug.Print bmfh.bfReserved2
Debug.Print bmfh.bfOffBits

End Sub

我的结果:
1CC14C
256
16777472
256
0
256

Herro 2004-01-16
  • 打赏
  • 举报
回复
to TechnoFantasy
知道是2字节, 但内存中看下来当中多出了2个字节, 不知道原因....
定义成long不但get数据出错, copy更不对了, 而且还不能显示图像.

to lk_cool
而后面的几个integer类型没有问题.

chenkangli 2004-01-16
  • 打赏
  • 举报
回复
VB中Integer占用的是二个字节,long才是4个字节,byte是一个字节!
lk_cool 2004-01-16
  • 打赏
  • 举报
回复
integer在不同的机器上的长度是不同的。

好像java中integer型在内存中的存放顺序也不同。
TechnoFantasy 2004-01-16
  • 打赏
  • 举报
回复
在VB中Integer占用的是两个字节,你应该定义成Long。

7,764

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧