Return to Snippet

Revision: 11910
at February 23, 2009 12:01 by pckujawa


Updated Code
C#
void cSharpMethod() {
    String myString = "ASCII/ANSI String in C#";
    cPlusPlusClass.cPlusPlusMethod(myString);
}

C++
int cPlusPlusMethod(System::String^ aString) {
    char* charPtr = (char*)Marshal::StringToHGlobalAnsi(aString).ToPointer();
    // Use it...
    Marshal::FreeHGlobal(IntPtr(charPtr)); // Free memory
}

Revision: 11909
at February 23, 2009 11:38 by pckujawa


Initial Code
C#
void cSharpMethod() {
    String myString = "ASCII/ANSI String in C#";
    cPlusPlusClass.cPlusPlusMethod(myString);
}

C++
int cPlusPlusMethod(System::String^ aString) {
    char* charPtr = (char*)Marshal::StringToHGlobalAnsi(aString).ToPointer();
}

Initial URL

                                

Initial Description
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](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtohglobalansi.aspx) from MSDN.

Good [information about native vs. managed types](http://blog.rednael.com/2008/08/29/MarshallingUsingNativeDLLsInNET.aspx).

Related [forum post](http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/5fe46030-76f7-4988-9ce3-fc21a30ee3a2/).

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

Initial Tags
c, Net

Initial Language
C#