从c#到c ++的封送数组,具有固定大小的缓冲区

时间:2015-04-13 06:36:41

标签: c# c++ struct pinvoke marshalling

我使用以下代码将结构数组封送到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);
}

为了填充我的结构,我使用以下代码:

//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;
   }
}

代码工作得很好,没有内存泄漏 如何确保在将像素编组到本机代码期间CLR不会来回复制像素阵列?

干杯,
多伦

2 个答案:

答案 0 :(得分:2)

你可以确定编组器没有复制阵列成员的方法是编组人员不知道阵列的大小。它根本无法编组数组内容。您只是传递固定数组的地址。不执行复制该阵列的内容。

答案 1 :(得分:0)

您可以使用In Attribute指定需要从调用者封送到被调用者的参数:

[DllImport("IPD.dll", EntryPoint = "process", CallingConvention = CallingConvention.Cdecl)]
public static extern Pixel* process([In] Pixel* pixels, int numPoints, uint processingFactor);