I'm transfering data between c++ and c# and I really need to have value-type arrays or list to pass the data directly. I don't mind them being a const expression. Is there a way to have an array which would behave like a c# struct or like a c++ std::array?
Edit: In the worst case i can use std::vector but i would prefer std::array because i really care about performance
If you're talking about arrays of primitive types (byte
, int
, etc.) then marshalling between C# and C++ is quite simple using fixed
:
unsafe
{
byte[] arr = new byte[1024];
fixed (byte* nativeArray = arr)
{
IntPtr ptr = (IntPtr)nativeArray;
// Pass ptr directly to C++ and use as an unsigned char*
}
}
Note this requires use of the unsafe
option when compiling.
The same works for int
, uint
, short
, ushort
, float
, double
, long
, and ulong
.
You MUST use the pointer on the C++ side immediately and either copy it to a native buffer or be done with it before returning. The point of fixed
is to make sure the memory isn't GC'd or moved while control is inside the fixed
block.