简体   繁体   English

在 C# 中的等效结构之间高效转换

[英]Efficiently convert between equivalent structs in C#

I am communicating between two libraries which use equivalent structs.我在两个使用等效结构的库之间进行通信。 For example:例如:

struct MyVector {
    public float x, y, z;
}

struct TheirVector {
    public float x, y, z;
}

Currently I am "casting" between these types by copying each of one's members into an instance of the other.目前,我通过将每个成员复制到另一个成员的实例中来在这些类型之间“转换”。 Knowing how C# stores structs in memory, isn't there a much more efficient way of doing this with pointers?知道 C# 如何在 memory 中存储结构,难道没有更有效的方法来使用指针吗?

Additionally, let's say I have two arrays of these equivalent structs:另外,假设我有两个 arrays 这些等效结构:

MyVector[] array1; // (Length 1000)
TheirVector[] array2; // (Length 1000)

Isn't there a way to copy the whole block of memory from array1 into array2?没有办法将memory的整个块从array1复制到array2吗? Or even better, could I treat the entirety of array1 as of type array2 without creating a copy in memory?或者更好的是,我可以将整个array1 视为array2 类型而不在memory 中创建副本吗?

I'm sure the answer requires pointers, but I have only used pointers in C++ and have no idea how C# implements them.我确定答案需要指针,但我只在 C++ 中使用过指针,不知道 C# 是如何实现它们的。

Does anyone have any examples on how to achieve something like this?有没有人有任何关于如何实现这样的目标的例子?

Thanks in advance!提前致谢!

Yes, if you're absolutely 100% sure that they have the same memory layout, you can coerce between them.是的,如果您绝对 100% 确定它们具有相同的 memory 布局,您可以在它们之间进行强制转换。 The preferred way of doing this (to avoid too much unsafe / pointers) is: spans.这样做的首选方法(以避免过多的unsafe /指针)是:spans。 For example:例如:

var theirs = MemoryMarshal.Cast<MyVector, TheirVector>(array1);

This gives theirs as a Span<TheirVector> , without copying any of the actual data.这将theirs作为Span<TheirVector>提供,而无需复制任何实际数据。 Spans have a very similar API to arrays/vectors, so most things you expect to work: should work exactly as you expect.跨度与数组/向量具有非常相似的 API,因此您希望工作的大多数事情:应该完全按照您的预期工作。 You simply have a typed reference to the same memory, using a different type.您只需使用不同的类型对相同的 memory 进行类型化引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM