title: Passing char * parameter to C++ dll function from C# GUI
body: <p>I have a cpp function as DLL file to read a file from certain file path and gives back "0" if success and other number if something failed:</p>
  
  <pre><code>short __stdcall ReadPx(char *filePath, MAP *map, int *num);
  </code></pre>
  
  <p>This function is defined in my C# as: </p>
  
  <pre><code>[DllImport("lib.dll", EntryPoint = "ReadPx", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
  public static extern System.Int16 ReadPx([MarshalAs(UnmanagedType.LPStr)] string filePath, ref MAP Map, ref Int32 numE);
  </code></pre>
  
  <p>And it is called in the main function as:</p>
  
  <pre><code>var pix = new MAP();
  int num = 1;
  string path = "C:/Users/Visual Studio 2015/Projects/testWrapper2/Map\0";
  System.Int16 Output = ReadPx(path, ref pix, ref num);
  Console.WriteLine(Output);
  </code></pre>
  
  <p>The function runs fine but gives an invalid file path error. I think the problem might be that in the C# code defines “String filePath” as Unicode (2 bytes per character), whereas the ReadPx expects a pointer to a simple ASCII string. That is why I tried some modifications shown below, but the file path error still there. </p>
  
  <pre><code>[DllImport("lib.dll", EntryPoint = "ReadPx", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
  public static extern System.Int16 ScReadPixMap(IntPtr filePath, ref PIXMAPENTRY pixMap, ref Int32 numEntries);
  
  IntPtr ptrCString = (IntPtr)Marshal.StringToHGlobalAnsi(path);
  System.Int16 output = ReadPx(ptrCString, ref pix, ref num);
  Marshal.FreeHGlobal(ptrCString);
  </code></pre>
  
  <p>Some thoughts and suggestions are appreciated. Thank you.</p>