C # DllImport and Marshaling char **

I am working in C # and I need to use this function from a C ++ dll:

extern "C" char IMPEXP __stdcall service_GetParameter ( const char* parameter, const int value_lenght, char** value ); 

I used it in C ++ code as follows:

 char *val = new char[256]; service_GetParameter("firmware_version", 255, &val); AnsiString FirmwareVersion = val; delete[] val; 

How to import this function and use it in C #?

Thank you in advance

+1
source share
2 answers

If this function allocates memory and makes the operator responsible for freeing it, I’m afraid that you will have to manage it manually: declare the parameter as ref IntPtr and use the methods of the Marshal class to get a String with a copy of the pointed data.

Then call the appropriate function to free memory (as Dirk said, we can no longer talk about it without additional information about the function).

If it really needs to be highlighted before the call, it should look something like this:

 [DllImport("yourfile.dll", CharSet = CharSet.Ansi)] public static extern sbyte service_GetParameter ( String parameter, Int32 length, ref IntPtr val); public static string ServiceGetParameter(string parameter, int maxLength) { string ret = null; IntPtr buf = Marshal.AllocCoTaskMem(maxLength+1); try { Marshal.WriteByte(buf, maxLength, 0); //Ensure there will be a null byte after call IntPtr buf2 = buf; service_GetParameter(parameter, maxLength, ref buf2); System.Diagnostics.Debug.Assert(buf == buf2, "The C++ function modified the pointer, it wasn't supposed to do that!"); ret = Marshal.PtrToStringAnsi(buf); } finally { Marshal.FreeCoTaskMem(buf); } return ret; } 
+2
source

I would start with something like this:

 [DllImport("yourfile.dll", CharSet = CharSet.Ansi] public static extern Int32 service_GetParameter([MarshalAs(UnmanagedType.LPStr)] String szParameter, Int32 value_length, [Out] StringBuilder sbValue); 
0
source

Source: https://habr.com/ru/post/1266018/


All Articles