Marshal C#类数组作为结构数组到C

时间:2011-11-07 12:47:45

标签: c# arrays interop struct marshalling

这是我的代码:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Foo
{
  UInt32 StartAddr;
  UInt32 Type;
}


[DllImport(DllName, EntryPoint="_MyFunc", CallingConvention = CallingConvention.Cdecl)]
static extern unsafe IntPtr MyFunc([MarshalAs(UnmanagedType.LPArray)] Foo[] Foos);


List<Foo> Foos = new List<Foo>();
Foo1 = new Foo();
Foo1.StartAddr = 1;
Foo1.Type = 2;
Foos.Add(Foo1);
MyFunc(Foos.ToArray());

在基于C的DLL中,我打印出Foos [0] .StartAddr和Foos [0] .Type的值。这很有效。

现在我想在struct中添加一个无参数构造函数,这意味着我必须切换到一个类。通过仅将C#声明从“struct”更改为“class”,会导致将损坏的值传递给基于C的DLL。

我相信这应该有效,但我认为我错过了一步。如何将C#类数组作为结构数组传递给C代码?

谢谢!安迪

1 个答案:

答案 0 :(得分:4)

如果您需要在结构中使用默认项,则可以向其添加静态属性

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct Foo
    {
      UInt32 StartAddr;
      UInt32 Type;

      public static Foo Default
      {
          get 
          {
               Foo result = new Foo();
               result.StartAddr = 200;
               result.Type = 10;
               return result;
          }
      }
    }

当您需要创建新的Foo结构时,只需调用Foo.Default

相关问题