在C#中,是否可以在不创建新数组的情况下将字节数组转换为其他类型? [英] In C#, is it possible to cast a byte array into another type without creating a new array?

查看:66
本文介绍了在C#中,是否可以在不创建新数组的情况下将字节数组转换为其他类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个byte []对象用作数据缓冲区.

I have a byte[] object that I'm using as a data buffer.

我想将其作为原始/非原始"结构的数组读取",而不复制内存中的byte []数据.

I want to "read" it as an array of a either primitive/non-primitive structs without duplicating the byte[] data in memory.

目标类似于:

byte[] myBuffer;

//Buffer is populated

int[] asInts = PixieDust_ToInt(myBuffer);
MyStruct[] asMyStructs = PixieDust_ToMyStruct(myBuffer);

这可能吗?如果可以,怎么办?

Is this possible? If so, how?

推荐答案

有可能吗?实际上,是的!

Is it possible? Practically, yes!

自.NET Core 2.1起,MemoryMarshal允许我们针对跨度执行此操作.如果您对跨度而不是数组感到满意,那么可以.

Since .NET Core 2.1, MemoryMarshal lets us do this for spans. If you are satisfied with a span instead of an array, then yes.

var intSpan = MemoryMarshal.Cast<byte, int>(myByteArray.AsSpan());

int跨度将包含byteCount/4个整数.

The int span will contain byteCount / 4 integers.

关于自定义结构...该文档声称转换的两面都需要原始类型".但是,您可以尝试使用ref struct并看到这是 actual 约束.如果它奏效,我不会感到惊讶!

As for custom structs... The documentation claims to require a "primitive type" on both sides of the conversion. However, you might try using a ref struct and see that is the actual constraint. I wouldn't be surprised if it worked!

请注意,引用结构仍然非常受限制,但是这种限制对于我们正在谈论的重新解释类型转换是有意义的.

Note that ref structs are still very limiting, but the limitation makes sense for the kind of reinterpret casts that we are talking about.

哇,约束要严格得多.它需要任何结构,而不是基元.它甚至不必是ref struct.如果您的结构在其层次结构中的任意位置包含引用类型,则只会抛出 runtime 检查.那讲得通.因此,这应该适用于您的自定义结构以及适用于int的结构.享受吧!

Wow, the constraint is much less strict. It requires any struct, rather than a primitive. It does not even have to be a ref struct. There is only a runtime check that will throw if your struct contains a reference type anywhere in its hierarchy. That makes sense. So this should work for your custom structs as well as it does for ints. Enjoy!

这篇关于在C#中,是否可以在不创建新数组的情况下将字节数组转换为其他类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆