简体   繁体   中英

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?

Additionally, let's say I have two arrays of these equivalent structs:

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

Isn't there a way to copy the whole block of memory from array1 into array2? Or even better, could I treat the entirety of array1 as of type array2 without creating a copy in memory?

I'm sure the answer requires pointers, but I have only used pointers in C++ and have no idea how C# implements them.

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. The preferred way of doing this (to avoid too much unsafe / pointers) is: spans. For example:

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

This gives theirs as a Span<TheirVector> , without copying any of the actual data. Spans have a very similar API to arrays/vectors, so most things you expect to work: should work exactly as you expect. You simply have a typed reference to the same memory, using a different type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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