使用固定大小的缓冲区封送从 C# 到 C++ 的结构数组

Marshaling array of structs from c# to c++ with fixed size buffer

本文关键字:C++ 数组 结构 缓冲区      更新时间:2023-10-16

我使用以下代码将结构数组封送到 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 不会来回复制像素数组?

干杯
多兰

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

可以使用 In 属性指定需要从调用方封送到被调用方的参数:

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