title: C# Calling C++ DLL Function which returns a struct
body: <p>I have an C++ dll which defines a struct and an dll call like this:</p>
  
  <pre><code>typedef const char* FString;
  
  typedef struct {
      FString version;
      FString build_no;
      FString build_type;
      FString build_date;
      FString build_info;
      FString comment;
  } FVersionInfo;
  
  extern "C" FAPI_EXPORT FVersionInfo CALLINGCONV fGetVersion(void);
  </code></pre>
  
  <p>On the c# side i using an dynamic loading:</p>
  
  <pre><code>    [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
      static extern int LoadLibrary(
          [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
  
      [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
      static extern IntPtr GetProcAddress(int hModule,
          [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
  
      [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
      static extern bool FreeLibrary(int hModule);
  
      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
      public struct FVersionInfo
      {
          public string Version;
          public string Build_No;
          public string Build_Type;
          public string Build_Date;
          public string Build_Info;
          public string Comment;
      }
  
      [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
      public delegate FVersionInfo fGetVersion();
  
      public fGetVersion GetVersion;
  
      FHandle = LoadLibrary(@pName);
      IntPtr intPtr;
      intPtr = GetProcAddress(FHandle, "fGetVersion");
      GetVersion = (fGetVersion)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(fGetVersion));
  </code></pre>
  
  <p>The calling code should be:</p>
  
  <pre><code>FVersionInfo version = new FVersionInfo();
  version = GetVersion();
  </code></pre>
  
  <p>My first problem is, that i become an "System.Runtime.InteropServices.MarshalDirectiveException" on the call of Marshal.GetDelegateForFunctionPointer in the c# loading part. </p>
  
  <p>I have then tested using IntPtr as struct return parameter like that:</p>
  
  <pre><code>[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
  public delegate IntPtr fGetVersion();
  </code></pre>
  
  <p>So i got the Marshal.GetDelegateForFunctionPointer to work, but later i've got the same problems with marshaling:</p>
  
  <pre><code>IntPtr DllValue = new IntPtr();
  FVersionInfo version = new FVersionInfo();
  DllValue = fGetVersion();
  Marshal.PtrToStructure(DllValue, FVersionInfo);
  </code></pre>
  
  <p>Here it crashes at the fGetVersion() call with "Managed Debugging Assistant 'PInvokeStackImbalance'". I think it means, that the stack is corrupted (imbalanced).</p>
  
  <p>I have tested with many variants of the structure definition, but no result.</p>
  
  <p>Any ideas or suggestions would be welcome!</p>