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:
short __stdcall ReadPx(char *filePath, MAP *map, int *num);
This function is defined in my C# as:
[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);
And it is called in the main function as:
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);
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.
[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);
Some thoughts and suggestions are appreciated. Thank you.