Saturday, February 12, 2011

Should I use Ansi or Unicode charset with dllimport?

When you use DllImport to import a function you can specify a CharSet to use. I noticed that in C#, C++ and visual basic the .Net runtime defaults to using Ansi instead of Unicode for this. So for any system call that has an A and a W version the A version will be called by default. .Net uses unicode internally and if I'm not mistaken new versions of windows also translate everything to unicode so this means a lot of extra marshalling overhead.

I have gotten into the habit of always specifying unicode here is this the right way to do things or will this cause problems?

  • If you use the ANSI variants, you will have problems if (for instance) there is a file with a name which cannot be represented in the ANSI codepage being used. The only downside with using Unicode is that your code might not work as well on the older Win9x versions of Windows (95, 98, and ME).

    There are a few functions where you will have to use ANSI, because they in fact use ASCII (GetProcAddress for instance).

    From CesarB

0 comments:

Post a Comment