title: Marshalling in c# ( Passing structure to an unmanaged type )
body: <p>I have a c++ dll which exposes the following function</p>
  
  <pre><code>long func(struct name * myname)
  {
       strcpy(myname-&gt;firstname,"rakesh");
       strcpy(myname-&gt;lastname,"agarwal");
       return S_OK;
  }
  
  struct name
  {
      char firstname[100];
      char lastname[100];
  }
  </code></pre>
  
  <p>I want to call this function from a C# application , so I do the following :</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  unsafe public struct name
  {
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst=100)]
      public string firstname;
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
      public string lastname;
  } ;
  
  
  [DllImport("C++Dll.dll")]
  public unsafe static extern long func(name[] myname);
  
  name[] myname = new name[1];
  func(myname);
  </code></pre>
  
  <p>The application builds successfully. When the C# application .exe is run, the function <code>func()</code> is called successfully and it is able to populate the fields successfully inside the dll. But when the function returns to the C# application, the variable <code>myname</code> still conatins null values for the struct fields(<code>firstname</code> and <code>lastname</code>).</p>
  
  <p>Please suggest changes so that I am able to populate the fields values of <code>myname</code> (so that after the function <code>func()</code> finishes execution, the variable <code>myname-&gt;firstname</code> contains "rakesh" and <code>myname-&gt;lastname</code> contains "agarwal".</p>
  
  <p>Note: StringBuilder cannot be used inside the structure.</p>