相关疑难解决方法(0)

C#不安全值类型数组到字节数组转换

我使用扩展方法将float数组转换为字节数组:

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;
}
Run Code Online (Sandbox Code Playgroud)

我知道数组是指向与元素类型和数量信息相关的内存的指针.此外,在我看来,如果没有像上面那样复制数据,就没有办法从字节数组转换到字节数组.

我明白了吗?甚至不可能编写IL来从指针,类型和长度创建数组而不复制数据?

编辑:谢谢你的答案,我学到了一些基础知识,并尝试了新的技巧!

在最初接受Davy Landman的回答之后,我发现虽然他出色的StructLayout hack确实将字节数组转换为浮点数组,但它却无法正常工作.展示:

[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public …
Run Code Online (Sandbox Code Playgroud)

c# arrays pointers unsafe type-conversion

10
推荐指数
2
解决办法
2万
查看次数

标签 统计

arrays ×1

c# ×1

pointers ×1

type-conversion ×1

unsafe ×1