Marshal C # Class Array as an array of structures for C

Here is my code:

[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()); 

In the C-based DLL, I print out the value Foos [0] .StartAddr and Foos [0] .Type. This works great.

Now I want to add a constructor without parameters to the structure, which means that I need to switch to a class. Due to the change in the C # declaration from "struct" to "class", the results in damaged values ​​are passed to the C-based DLL.

I believe this should work, but I believe that I am missing a step. How to pass an array of C # classes as an array of structures into C code?

Thanks! Andy

+4
source share
1 answer

If you need a default element in your structure, you can add a static property to it

  [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; } } } 

And when you need to create a new Foo struct, just call Foo.Default

+4
source

Source: https://habr.com/ru/post/1379993/


All Articles