4

In one of the post Titled "Call a c++ method that returns a string, from c#"

Its said that , to make the following Pinvoke to work change the C++ signature to as

extern "C" REGISTRATION_API void calculate(LPSTR msg) 

C++ code

extern "C" REGISTRATION_API void calculate(char* msg) 

C# code

[DllImport("thecpp.dll", CharSet=CharSet.Ansi)] 
static extern void calculate(StringBuilder sMsg); 

How can stringBuilder which is a class ,convertd to long ptr to string .(but this is the accepted answer)

Shouldnt we use use IntPtr as below ?

extern "C" REGISTRATION_API void calculate(Intptr msg) 
jdehaan
  • 19,700
  • 6
  • 57
  • 97
Somaraj
  • 151
  • 2
  • 5

1 Answers1

8

Look for the section marked "Passing Strings", the marshaler has got some added smarts to do this trick.
http://msdn.microsoft.com/en-us/library/aa446536.aspx

To solve this problem (since many of the Win32 APIs expect string buffers) in the full .NET Framework, you can, instead, pass a System.Text.StringBuilder object; a pointer will be passed by the marshaler into the unmanaged function that can be manipulated. The only caveat is that the StringBuilder must be allocated enough space for the return value, or the text will overflow, causing an exception to be thrown by P/Invoke.

Carl Reinke
  • 345
  • 2
  • 12
Gishu
  • 134,492
  • 47
  • 225
  • 308
  • That link goes to the .NET **Compact** Framework. Does it also apply to the .NET Framework, and is there a documentation as well? – ygoe Aug 15 '16 at 15:39
  • I believe it does - I have written code that uses this & doesn't run on the Compact framework. Did you give it a try ? The last section on this page also confirms this https://msdn.microsoft.com/en-us/library/s9ts558h(v=vs.110).aspx – Gishu Aug 15 '16 at 20:28
  • I did try, but (as I later found out) with a function that is special in that it allocates the memory and expects the caller to free it, `FindMimeFromData`. This doesn't seem to work with StringBuilder, I only got garbage as a result. – ygoe Aug 16 '16 at 05:57
  • @ygoe Is the native function allocating a string? The functions i called had corresponding freeXXX functions (that deallocated the native memory allocated) that had to be called for cleanup. – Gishu Aug 22 '16 at 05:04
  • Yes it is, but the docs say I have to call some generic FreeXXX method to free the memory, and so do all the samples I could find. Works well. – ygoe Aug 23 '16 at 06:15