copy from managed class to native struct
<p>I need to fill native structs from managed classes. Following technique (1. copy managed data into managed byte array, 2. use memcopy to fill native struct) I found to be a common solution for this.
I assume the reason why following code doesn't work is that I use managed classes not managed structs. Having managed classes is a requirement in my project. Can I make this code work using managed classes, or must I switch to managed structs  ?</p>

<p>this is the c# managed class:</p>

<pre><code>[StructLayout(LayoutKind.Sequential)]
public class man_s
    {
    public man_s()
    {
        // (do something which i can't do in a struct!)
    }

    // should go into a one-byte native bool
    [MarshalAs(UnmanagedType.I1)]
    public bool flag1;

    public Int32 a;

    public Int32 b;
    };
</code></pre>

<p>... the native cpp struct:</p>

<pre><code>struct nat_s
    {
    public:
            bool flag1;
            __int32 a;
            __int32 b;
    };
</code></pre>

<p>... the code which should copy the managed data into the native struct:</p>

<pre><code>// setup some managed data
man_s^ mng = man_s();
    mng-&gt;flag1 = true;
    mng-&gt;a = 10;
    mng-&gt;b = 20;

    nat_s nat;
    int s = sizeof(nat);

    // size check is ok!
    System::Diagnostics::Debug::Assert(sizeof(nat) == System::Runtime::InteropServices::Marshal::SizeOf(mng));

    // copy into managed byte array
    array&lt;byte&gt;^ byteArray = gcnew array&lt;byte&gt;(s);
    System::Runtime::InteropServices::Marshal::Copy(IntPtr((void*)(&amp;mng)), byteArray, 0, s);

    // this doesn't bring up the expected results
    pin_ptr&lt;byte&gt; start = &amp;byteArray[0];
    memcpy(&amp;nat, start, s);

    // does not work either
    System::Runtime::InteropServices::Marshal::Copy(byteArray, 0, IntPtr((void*)(&amp;nat)), s);enter code here
</code></pre>