Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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 of Foos[0].StartAddr and Foos[0].Type. This works great.

Now I want to add a parameterless constructor to the struct which means I have to switch to a class. By only changing the C# declaration from "struct" to "class" results in corrupted values being passed to the C-based DLL.

I believe this should work but I presume I am missing a step. How can I pass an array of C# classes as a array of structs to C code?

Thanks! Andy

share|improve this question
1  
Yes, won't work. The array will be marshaled as Foo** instead of Foo*. An array of pointers to Foo. No clean workaround either, manual marshaling is very ugly here. Don't do this if you can't change the C code. – Hans Passant Nov 7 '11 at 13:00

1 Answer 1

up vote 4 down vote accepted

If you need default item in your struct you can add 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 new Foo struct just call Foo.Default

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.