We help IT Professionals succeed at work.

How to convert a C++ "char*" to a C# "String"?

Finch
Finch asked
on
Medium Priority
2,282 Views
Last Modified: 2008-01-09
I have a DLL written in C++ that transfers a character array (char*) and I need to copy this character array into a C# String. I use Visual Studio 2005 and C#.
Comment
Watch Question

Carl TawnSenior Systems and Integration Developer
CERTIFIED EXPERT
Commented:
The constructor for the string type accepts a char* as a parameter so you should just be able to use something like:

    string myString = new string("your char*");

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Commented:
See Marshal.PtrToStringAnsi Method. Show C++ function prototype for details.

Author

Commented:
Both answers given work similarly, and the string is now available at the C# level. But now I am struggling with a runtime error when the return to the DLL is executed. So this has probably turned into a "Marshalling" question, I've bumped the reward points for this question accordingly.  I get the following error message as I return from the C# to the C++ DLL:

      Runtime Check Failure #0: The value of ESP was not properly saved across a function call.....

My function call prototype on the C++ DLL side is:
    typedef void(*MyCallbackFunction)(char*, int);

My Callback function on the C# side looks like this:
    public void MyCallbackFunction(IntPtr Message, int ErrorLevel);

Commented:
So, what exactly C++ function does, and what is your C# code? Working with interoperability, it is important to know what is parameters type (in, out), what function allocates memory, what function is responsible to release memory etc. Give enough information.
theGhost_k8Database Consultant
CERTIFIED EXPERT

Commented:
try n use for Marshal class
marshal.ptrtostring function could come to rescue..
Daniel Van Der WerkenIndependent Consultant
CERTIFIED EXPERT

Commented:
Are you using Platform Invoke?  Sounds like you're trying to use an unManaged DLL without using P/Invoke.  

http://msdn2.microsoft.com/en-us/library/fzhhdwae.aspx
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.