Easy C# String problem....

  • Thread starter Thread starter news
  • Start date Start date
N

news

Hi Guys,

Im trying to pass a string from a C++ DLL back into a C# application.

In the C++ DLL the string is a char array,

static char
myArray [2048];

extern "C" __declspec(dllexport) char *getMyString (void)
{
sprintf (myArray, "the string I want");

return myArray;
}

In the C# Application I have this :-

[DllImport("myDll.Dll", CharSet=CharSet.Auto)] public static extern char
[] getMyString();


This all seems to work ok but I don't know how to get this char [] into a C#
string...

Any help appreciated.

Thanks ,

Todd.
 
This all seems to work ok but I don't know how to get this char [] into a C#
string...

Well if it was that easy you would use the String constructor that
takes a char[]. But in fact you have to declare it as

[DllImport("myDll.Dll", CharSet=CharSet.Auto)] public static extern
IntPtr getMyString();

and then use Marshal.PtrToStringAnsi() to retrieve the string from the
returned pointer.


Mattias
 
Back
Top