October 18, 2004

What is an ANSI string?

The last post leads me to the question: What is an ANSI string?

There is no comment what exactly the functions PtrToStringAnsi or StringToHGlobalAnsi are doing…

It seems that it is the same conversion, as if you would specify the CharSet=CharSet.Ansi in an DllImportAttribute, because it uses a simple native RtlMoveMemory in kernel32 to do the conversion. So the question is now: What is CharSet=CharSet.Ansi doing?

And this is stated in the docu for CharSet enumeration as Marshal strings as multiple-byte character strings.

If you start an debugger (like windbg) and dig into the deepness of the conversion, you will see that it internally calls MultiByteToWideChar with CP_ACP (Ansi codepage). This is hardcoded in the function mscorwks!ML_CSTR_C2N_SR::DoConversion.

If you need an other codepage in the conversion to unmanaged char, you could use the following code:

  System::String *mstr = S"Hello world!";
  char *ustr;
  int codepage = 1252;

  unsigned char c __gc[] =
  unsigned char __pin *cc = &c[ 0 ];
  ustr = new char[c->get_Length()+1];
  strcpy(ustr, (char*) cc);

  // now do something with the converted string

  delete [] ustr;

Posted 3 years, 3 months ago on October 18, 2004
The trackback url for this post is http://blog.kalmbachnet.de/bblog/trackback.php/19/

Comments have now been turned off for this post