Easy C# String problem....

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.
 
M

Mattias Sjögren

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top