title: Calling c++ dll functions returning char* from c#. Cannot use DllImport()
body: <p>I have a c++ dll with 2 functions</p>
  
  <pre><code>const char* getVersionText1(void);
  void        getVersionText2(const char** res);
  </code></pre>
  
  <p>Both function return a string describing the version of the product. First function returns it as const char* (which means it allocates and deal locates it internally) and the second one gets a pointer to char* and just sets it to point to a char* describing the version.</p>
  
  <p>I want to call those functions from C# and display the text.
  I cant use [dllimport ...] style since the order of the calling of functions is important. I first call constructor than getVersion and finally the destructor. So dll must be loaded to memory first. </p>
  
  <p>Can you please post the few lines of codes that print the text for both functions.
  I am new to C#, so sorry if you find my code problematic
  I tried</p>
  
  <pre><code>static class NativeMethods{
      [DllImport("kernel32.dll")]
      public static extern IntPtr LoadLibrary(string dllToLoad);
      [DllImport("kernel32.dll")]
      public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
      [DllImport("kernel32.dll")]
      public static extern bool FreeLibrary(IntPtr hModule);
  }
  class Program{
      // Define function pointers to entires in DLL
      [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr getVersionText1();
      [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void getVersionText2(IntPtr );
      static void Main(string[] args){
          // Pointers to functions of DLL.
          getVersionText1 f1;
          getVersionText2 f2;
          IntPtr pDll = NativeMethods.LoadLibrary("p:\\my.dll");
          IntPtr pAddressOfFunctionToCall;
          pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "getVersionText1 ");
          f1 = (getVersionText1)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(getVersionText1));
          pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "getVersionText2 ");
          f2 = (getVersionText2)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(getVersionText2));
  
          // Here I don't know what to do. It doesn't work ????
          IntPtr verText = f1();
          String s = Marshal.PtrToStringAuto(verText);
          Console.WriteLine(s);   // Doesnt work
          // And how to use the second function. How do I sent a pointer to char* ???
      }
  }
  </code></pre>