获得Memory< byte>可变结构的正确方法/Span< byte> ;? [英] Proper way to get a mutable struct for Memory<byte> / Span<byte>?
问题描述
对于网络协议的实现,我想利用新的 Memory
和 Span
类来实现缓冲区的零复制,同时通过结构
.
For a network protocol implementation I want to make use of the new Memory
and Span
classes to achieve zero-copy of the buffer while accessing the data through a struct
.
我有以下人为的例子:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Data
{
public int IntValue;
public short ShortValue;
public byte ByteValue;
}
static void Prepare()
{
var buffer = new byte[1024];
var dSpan = MemoryMarshal.Cast<byte, Data>(buffer);
ref var d = ref dSpan[0];
d.ByteValue = 1;
d.ShortValue = (2 << 8) + 3;
d.IntValue = (4 << 24) + (5 << 16) + (6 << 8) + 7;
}
结果是 buffer
填充了 7、6、5、4、3、2、1
,这是所需要的,但是我很难想象 MemoryMarshal.Cast
是执行此操作的唯一方法(禁止任何需要 unsafe
关键字的内容).我尝试了其他方法,但无法弄清楚如何将它们与 ref struct
(不能用作泛型类型参数)一起使用,或者如何获取位于实际的缓冲区,而不是副本(副本上的任何突变都不会反映在缓冲区上).
The result is that buffer
is filled with 7, 6, 5, 4, 3, 2, 1
, which is as desired, but I can hardly imagine that MemoryMarshal.Cast
is the only way (bar anything requiring the unsafe
keyword) to do this. I tried some other methods, but I can't figure out how to use them with either a ref struct
(which can't be used as generic type argument) or how to get a struct that's in the actual buffer and not a copy (on which any mutations made are not reflected in the buffer).
有没有更简单的方法从缓冲区中获取此可变结构?
Is there a some easier way to get this mutable struct from the buffer?
推荐答案
Oof.看起来 MemoryMarshal.Cast
是以前的 NonPortableCast
扩展方法(来自:
Oof. It looks like MemoryMarshal.Cast
is what used to be the NonPortableCast
extension method (from: this commit), in which case - yes, that's the appropriate way to thunk between layouts of spans, most commonly (but not exclusively) like in this case - between byte
and some struct
.
这篇关于获得Memory< byte>可变结构的正确方法/Span< byte> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!