c# - 将值分配给 C++ 中的结构到从 C# 传递的结构时出现问题

标签 c# c++ dll struct interopservices

我在 C# 中有一个函数,它将结构数组传递到用 C++ 编写的 DLL 中。该结构是一组整数,当我读出 DLL 中的数据时,所有值都很好。但是,如果我尝试从 C++ 写入元素,当我尝试读取然后返回到 C# 时,值永远不会显示。

C#

[StructLayout(LayoutKind.Sequential)]
struct Box
{
  public int x;
  public int y;
  public int width;
  public int height;
}

[StructLayout(LayoutKind.Sequential)]
struct Spot
{
  public int x;
  public int y;
}

static void TestCvStructs()
{
  int len = 100;
  Box[] r = new Box[len];
  Spot[] p = new Spot[len];

  for (int i = 0; i < len; i++)
  {
    r[i].x = i*10;
    r[i].y = i * 200;
    r[i].width = r[i].x * 10;
    r[i].height = r[i].y * 100 + r[i].x * 5;

    p[i].x = i * 8;
    p[i].y = i * 12;
  }

  PassCvStructs(len, r, p);

  for (int i = 0; i < len; i++)
  {
    Console.WriteLine("Point/x:{0} Boxes/x{1}", p[i].x, r[i].x );
  }
}

[DllImport(dll)]
private static extern int PassSomeStructs(int count, Box[] boxes, Spot[] points);

C++

typedef struct Box
{
  int x;
  int y;
  int width;
  int height;
} Box;

typedef struct Spot
{
  int x;
  int y;
} Spot;

CPPDLL_API int PassSomeStructs(int arrayLength, Box *boxes, Spot *points)
{
  for(int i = 0; i < arrayLength; ++i)
  {
    printf("Group:%i\n", i);
    printf("Rect - x:%i y:%i width:%i length:%i\n", boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);
    printf("Point - x:%i y:%i\n", points[i].x, points[i].y);
    printf("\n");

    points[i].x = 3;
    boxes[i].x = 1;
  }
  return 0;
}

最佳答案

来自MDSN article关于编码数组:尝试在数组类型上设置以下属性。这通常用于从 C++ 调用 C#,但也可能需要将更新的值返回到 C#。

[DllImport(dll)]
private static extern int PassSomeStructs(int count, 
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] Box[] boxes, 
    [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] Spot[] points);

另请参阅本文以获取成功的双向编码示例:

http://social.msdn.microsoft.com/forums/en-US/csharplanguage/thread/ff0123d0-506b-4de2-bfb5-f690c9358826/

关于c# - 将值分配给 C++ 中的结构到从 C# 传递的结构时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1903173/

相关文章:

C++:可以使用 decltype 从我的头文件中复制类型吗?

c++ - 比较 C++11 中的数组地址

c# - 从 C# 调用具有复杂用户定义类型 (UDT) 的 VB6 DLL 函数

c# - 为什么 .Net 最佳实践是将自定义属性设计为密封的?

C++ : operator new and default constructor

c# - 使用 IValidatableObject 将数据验证添加到 WPF 和 C# 中的 Entity Framework 实体

powershell - 找不到powershell dll方法

.net - Visual Studio 2008 : Creating Single DLL from Solution with Many Projects

c# - 如何通过 C# 返回 Task<List<string>>?

c# - ContinueWith 丢失 SynchronizationContext