title: DllImport and char Marshaling
body: <p>I'm newbie at C# and Marshaling. I need to use my C func in C#, but i have an incorrect return value from C func (or I don't know how to convert it to correct answer).</p>
  
  <p>C source:</p>
  
  <pre><code>#include "main.h"
  
  char *Ololo(char *arg, int &amp;n3)
  {
      char *szRet;
      szRet=(char*)malloc(strlen(arg)+1);
      strcpy(szRet,arg);
      n3 = strlen(szRet);
      return szRet;
  }
  </code></pre>
  
  <p>C header:</p>
  
  <pre><code>extern "C" __declspec(dllexport) char *Ololo(char *arg, int &amp;n3);
  </code></pre>
  
  <p>C# source:</p>
  
  <pre><code>class Program
  {
      [DllImport(@"F:\Projects\service\dll\testDLL2.DLL", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
      public static extern IntPtr Ololo([In] char[] arg, ref Int32 n3);
  
      static void Main(string[] args)
      {
          string n1 = "ololo";
          char[] chars = new char[n1.Length];
          chars = n1.ToCharArray();
          Int32 n3 = 0;
          IntPtr result;
          result = Ololo(chars, ref n3);
          string n4 = Marshal.PtrToStringUni(result,n3);
          Console.WriteLine(n4);
      }
  }
  </code></pre>
  
  <p>I've got return something like "o?? ?" </p>
  
  <p>Sorry for bad English</p>
  
  <p>----------------------Solved-----------------------</p>
  
  <pre><code>class Program
      {
          [DllImport(@"F:\Projects\service\dll\testDLL2.DLL", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
          public static extern IntPtr Ololo([MarshalAs(UnmanagedType.LPStr)]string arg, ref Int32 n3);
  
          static void Main(string[] args)
          {
              string n1 = "ololo";
              Int32 n3 = 0;
              int n2 = n1.Length;
              IntPtr result;
              result = Ololo(n1, ref n3);
              string n4 = Marshal.PtrToStringAnsi(result, n3);
              Console.WriteLine(n4);
          }
      }
  </code></pre>
  
  <p>That works fine. In n3 i ve got 5 and in n4 ololo! Thank s for quick answers!</p>