Naming conventions used in Platform Invocation in .NET

163 Views Asked by At

I have been using the Microsoft P/Invoke Interop Assistant tool to generate some structures, delegates etc. from native C/C++ code.

An example of one of these is a function pointer (delegate), which resolves in managed code to the following names:

EnumCalendarInfoProcA
EnumCalendarInfoProcW
EnumCalendarInfoProcExA
EnumCalendarInfoProcExW

Can anyone explain the difference between A and W and ExA and ExW?

2

There are 2 best solutions below

3
On BEST ANSWER

Some functions have several formats. Either Ascii (MessageBoxA) or wide char / unicode (MessageBoxW). When a function does the same, but more, the name usually gets a postfix 'Ex', and probably means extended.

Like the following functions

MessageBox: http://msdn.microsoft.com/en-us/library/windows/desktop/ms645505(v=vs.85).aspx

MessageBoxEx: http://msdn.microsoft.com/en-us/library/windows/desktop/ms645507(v=vs.85).aspx

where MessageBoxEx is extended by the parameter wLanguageId.

0
On

You have to be a bit careful with the PInvoke Interop Assistant. The declarations it generates are completely auto-generated and unedited. It tends to produce fairly awkward results as a result, you at least need to compare with an edited source of declarations such as available from the pinvoke.net website and the MSDN library.

The A and W versions exist because the function manipulates strings. Old versions of Windows in the 9x branch were not Unicode enabled. They used the A versions, strings with 8-bit encoded characters. That stopped being relevant with the quick and well deserved demise of Windows ME. All versions of Windows that you'll ever run into today are from the NT branch and they are Unicode enabled at the core.

The pinvoke marshaller already knows how to properly choose between the A and the W versions, based on the CharSet property in the [DllImport] attribute. Sadly the default is still Ansi, big mistake, you should always specify CharSet.Auto and use the name without the W. The exact name doesn't actually matter for EnumCalendarInfoProc since it is a callback prototype, you declare it as a delegate. You can pick any name.

The difference between EnumCalendarInfoProc and EnumCalendarInfoProcEx is well explained in the MSDN article, the Ex version has an extra argument. Which one you need to use is determined by the api function you use to start enumerating. Either pick EnumCalendarInfo() or EnumCalendarInfoEx(). The latter one makes sense. And do note the ExEx version, available on Vista and up. Culture changes faster than Microsoft's ability to create Exes ;)

Apply CharSet.Auto on both the delegate and the function declaration.