使用固定大小的缓冲区封送从 C# 到 C++ 的结构数组
Marshaling array of structs from c# to c++ with fixed size buffer
我使用以下代码将结构数组封送到 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);
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '