Consider a struct like System.Drawing.Point - one with LayoutKind.Sequential and containing only primitive members. I have a C# array of such structs.
I'm passing it to an (unmanaged) C++ function via P/Invoke. On the C++ side there's a corresponding definition of the struct (e.g. struct Point { int x, y; };
). The function takes a Point*
arg.
My question is, in what cases does the CLR copy the data and in what cases does it just pin it? Variables include:
Point*
or Point[]
/ Point[,]
fixed(Point* pointer = array)
or notI want to avoid the copying because it's slow.
I don't have much experience with pinning, but, according to my reading of MSDN, your structs should be pinned and not copied. Relevant refs:
From #2:
Formatted blittable classes have fixed layout (formatted) and common data representation in both managed and unmanaged memory. When these types require marshaling, a pointer to the object in the heap is passed to the callee directly.
And your Point struct is given as an example in #3, so it qualifies as a blittable type.
I noticed some overhead to pinning objects here, but that was for a fixed byte[]
, which may be different to your Point[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With