MarShal.Copy

guzicheng1990 2012-03-12 10:58:35
为什么用MarShal.Copy时,我传Byte[]类型可以,用float[]就不可以了呢?
附代码:
int iWidth = col;
int iHeight = row;

Bitmap Result = new Bitmap(iWidth, iHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
Rectangle rect = new Rectangle(0, 0, iWidth, iHeight);

System.Drawing.Imaging.BitmapData bmpData = Result.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

IntPtr iPtr = bmpData.Scan0;

int iStride = bmpData.Stride;
int offset = iStride - iWidth;
int iBytes = iWidth * iHeight;
int posScan = 0;
int posReal = 0;

float[] PixelValues = new float[iBytes];//byte[] pixelValues = new byte[scanBytes]; 

//System.Runtime.InteropServices.Marshal.Copy(iPtr, PixelValues, 0, iBytes);

for (int i = 0; i < col ; i++)
{
for (int j = 0; j < row; j++)
{
PixelValues[posScan++] = arr[posReal++];//byte 0~255 有负值
}
posScan += offset;
}

System.Runtime.InteropServices.Marshal.Copy(PixelValues, 0, iPtr , iBytes);//报错!尝试读取或写入受保护的内存。这通常指示其他内存已损坏
Result.UnlockBits(bmpData);
...全文
323 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
guzicheng1990 2012-03-12
  • 打赏
  • 举报
回复
还有那个没有考虑对齐因素是什么意思呀?

guzicheng1990 2012-03-12
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 gomoku 的回复:]
直接原因是一个float占4个bytes。
Marshal.Copy(iPtr, PixelValues, 0, iBytes);
将要求拷贝4*iBytes的字节,而iPtr无法提供。

另:
1、int iBytes = iWidth * iHeight;有误,没有考虑对齐因素。
2、Marshal.Copy(iPtr...有误,iPtr不一定总是指向数据头,也可能指向最后一行。
……
[/Quote]

非常感谢你的回答。
那请问应该怎么办啊?

int iBytes = iWidth * iHeight * 4; 也不行唉
难道这样说就是不能传float么?
gomoku 2012-03-12
  • 打赏
  • 举报
回复
直接原因是一个float占4个bytes。
Marshal.Copy(iPtr, PixelValues, 0, iBytes);
将要求拷贝4*iBytes的字节,而iPtr无法提供。

另:
1、int iBytes = iWidth * iHeight;有误,没有考虑对齐因素。
2、Marshal.Copy(iPtr...有误,iPtr不一定总是指向数据头,也可能指向最后一行。
guzicheng1990 2012-03-12
  • 打赏
  • 举报
回复
报错那句 如果PixelValues定义Byte[] 传进去就不报错

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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