我使用扩展方法将浮点数组转换为字节数组:
public static unsafe byte[] ToByteArray(this float[] floatArray, int count)
{
int arrayLength = floatArray.Length > count ? count : floatArray.Length;
byte[] byteArray = new byte[4 * arrayLength];
fixed (float* floatPointer = floatArray)
{
fixed (byte* bytePointer = byteArray)
{
float* read = floatPointer;
float* write = (float*)bytePointer;
for (int i = 0; i < arrayLength; i++)
{
*write++ = *read++;
}
}
}
return byteArray;
}
我知道数组是指向与元素类型和数量信息相关联的内存的指针。此外,在我看来,如果不复制上述数据,就无法在字节数组之间进行转换。
我明白了吗?甚至不可能编写 IL 来根据指针、类型和长度创建数组而不复制数据吗?
编辑:感谢您的回答,我学习了一些基础知识并尝试了新技巧!
在最初接受 Davy Landman 的回答后,我发现虽然他出色的 StructLayout hack 确实将字节数组转换为浮点数组,但反过来却行不通。展示:
[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
[FieldOffset(0)]
public Byte[] Bytes;
[FieldOffset(0)]
public float[] Floats;
}
static void Main(string[] args)
{
// From bytes to floats - works
byte[] bytes = { 0, 1, 2, 4, 8, 16, 32, 64 };
UnionArray arry = new UnionArray { Bytes = bytes };
for (int i = 0; i < arry.Bytes.Length / 4; i++)
Console.WriteLine(arry.Floats[i]);
// From floats to bytes - index out of range
float[] floats = { 0.1f, 0.2f, 0.3f };
arry = new UnionArray { Floats = floats };
for (int i = 0; i < arry.Floats.Length * 4; i++)
Console.WriteLine(arry.Bytes[i]);
}
似乎 CLR 认为这两个数组具有相同的长度。如果结构是从浮点数据创建的,则字节数组的长度太短了。