在C#中将int []转换为byte []类型的指针
问题描述:
我需要将int []转换为byte []指针.为了能够逐个像素地填充WriteableBitmap的条目,需要执行以下操作:
I require to convert int[] to byte[] pointer. The above is required in order to be able to populate the entries of a WriteableBitmap pixel by pixel as below:
//previewBuffer1 is of type byte[]
WriteableBitmap wb1 = new WriteableBitmap(nVidWidth, nVidHeight);
int k=0;
// wb1.Pixels is of type int[] by default
byte* data = (byte*) wb1.Pixels; // ****THIS DOESN'T WORK. THROWS ERROR. HOW CAN I ACCOMPLISH THIS***
for (int i=0; i<nVidHeight; i++){
for (int j=0; j<nVidWidth; j++){
byte grayscaleval = previewBuffer1[k];
data [4*k] = grayscaleval ;
data [4*k + 1] = grayscaleval ;
data [4*k + 2] = grayscaleval ;
k++;
}
}
如何获取类型为int []的wb1.Pixels的字节*指针?
How do I get a byte* pointer for wb1.Pixels which is of type int[]?
答
Sounds like you want to treat each int
in your array as sequence of bytes - how about BitConverter.GetBytes
?
byte[] bytes = BitConverter.GetBytes(intValue);
如果要避免数组复制等操作,请使用允许使用指针的 unsafe
(您需要在项目属性中选中允许不安全代码"复选框):
If you want to avoid array copying etc, use unsafe
which allows pointers (you'd need to tick the "Allow unsafe code" checkbox in project properties):
unsafe static void UnsafeConvert(int value)
{
byte* bytes = (byte*)&value;
byte first = bytes[0];
...
}