The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,373 other followers

P/Invoke: usually you need CharSet.Auto (via: .NET Column: Calling Win32 DLLs in C# with P/Invoke)

Posted by jpluimers on 2012/02/28

I don’t do P/Invoke often, and somehow I have trouble remembering the value of CharSet to pass with DllImport.

In short, pass CharSet.Auto unless you P/Invoke a function that is specific to CharSet.Ansi or CharSet.Unicode. The default is CharSet.Ansi, which you usually don’t want:

when Char or String data is part of the equation, set the CharSet property to CharSet.Auto. This causes the CLR to use the appropriate character set based on the host OS. If you don’t explicitly set the CharSet property, then its default is CharSet.Ansi. This default is unfortunate because it negatively affects the performance of text parameter marshaling for interop calls made on Windows 2000, Windows XP, and Windows NT®.

The only time you should explicitly select a CharSet value of CharSet.Ansi or CharSet.Unicode, rather than going with CharSet.Auto, is when you are explicitly naming an exported function that is specific to one or the other of the two flavors of Win32 OS. An example of this is the ReadDirectoryChangesW API function, which exists only in Windows NT-based operating systems and supports Unicode only; in this case you should use CharSet.Unicode explicitly.

–jeroen

via: .NET Column: Calling Win32 DLLs in C# with P/Invoke.

3 Responses to “P/Invoke: usually you need CharSet.Auto (via: .NET Column: Calling Win32 DLLs in C# with P/Invoke)”

  1. […] The Charset is almost always CharSet.Auto as that works far better than the default. […]

  2. Warren P said

    Does ANYONE care about Win9x anymore?

    W

  3. David Heffernan said

    If you don’t care about Win 9x, and I don’t, then CharSet.Unicode seems to convey more meaning to me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

 
%d bloggers like this: