Reputation: 515
I am using the following code to marshal an array of structs to c++:
[DllImport("IPD.dll", EntryPoint = "process", CallingConvention = CallingConvention.Cdecl)]
public static extern Pixel* process(Pixel* pixels, int numPoints, uint processingFactor);
[StructLayout(LayoutKind.Sequential)]
public unsafe struct Pixel
{
public fixed byte x[3];
public uint numebrOfPixels;
}
...
Pixel[] pixels = extractPixels(image);
fixed (Pixel* ptr = pixels)
{
Pixel* result = process(ptr, pixels.Length,processingFactor);
}
In order to populate my struct I am using the following code:
//Looping and populating the pixels
for(i=0;i<numOfPixels;i++)
{
fixed (byte* p = pixels[i].x)
{
p[0] = r;
p[1] = g;
p[2] = b;
}
}
The code works just fine with no memory leaks.
How can I be sure the during marshaling the pixels to the native code the CLR doesn't copy the pixels array back and forth?
Cheers,
Doron
Upvotes: 1
Views: 279
Reputation: 612954
The way you can be sure that the marshaller doesn't copy members of the array is that the marshaller doesn't know the size of the array. It is simply not capable of marshalling the array contents. You are simply passing the address of a pinned array. No copying of the content of that array is performed.
Upvotes: 2
Reputation: 357
You can use the In Attribute to specify an argument that needs to be marshaled from the caller to the callee:
[DllImport("IPD.dll", EntryPoint = "process", CallingConvention = CallingConvention.Cdecl)]
public static extern Pixel* process([In] Pixel* pixels, int numPoints, uint processingFactor);
Upvotes: 0