c# - 将 C# 类数组作为结构数组编码到 C

标签 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 的值。这很好用。

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

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

谢谢!安迪

最佳答案

如果你需要结构中的默认项,你可以向它添加静态属性

    [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

关于c# - 将 C# 类数组作为结构数组编码到 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8036719/

相关文章:

com - .NET 4.0 beta 2 中的 PIA 嵌入是否已损坏?

LinqToExcel : Distinct values in excel column

c# - 有没有办法在 WPF 窗口内托管 DirectX12 应用程序?

c# - c#中如何将DataTable中的值转换为字符串数组

java - 在 java 中,是否可以从字符串命名数组?

c# - 检查 Canvas Child 是否存在 : by tag

php - 如何在不指定索引号的情况下在 PHP 中构建对象数组?

java - 如何使用 "for"初始化具有多个值的整数数组

c# - 如何为 IEnumerable<dynamic> 赋值

c# - Prism EventAggregator 异常 - 必须在 UI 线程上构造