Posted By

pckujawa on 02/23/09


Tagged

c Net csharp


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

umang_nine
paelgr
khouser
danfinrud55


Pass a string from C# to a C++ DLL in .NET (and get a pointer to the string's chars)


 / Published in: C#
 

Specifically, this code enables you to pass a string from C# into C++ managed code and then get a C++ pointer to the string's chars.

Marshal.StringToHGlobalAnsi Method from MSDN.

Good information about native vs. managed types.

Related forum post.

  1. C#
  2. void cSharpMethod() {
  3. String myString = "ASCII/ANSI String in C#";
  4. cPlusPlusClass.cPlusPlusMethod(myString);
  5. }
  6.  
  7. C++
  8. int cPlusPlusMethod(System::String^ aString) {
  9. char* charPtr = (char*)Marshal::StringToHGlobalAnsi(aString).ToPointer();
  10. // Use it...
  11. Marshal::FreeHGlobal(IntPtr(charPtr)); // Free memory
  12. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: dadajay on February 15, 2010

gud

You need to login to post a comment.