Updating Win32 API Calls

23. November 2006 05:30 by Jaguilar in General  //  Tags:   //   Comments (0)

The Visual Basic Upgrade Companion allows you to convert calls to the Win32 API from Visual Basic 6 to C#. API calls in VB6 have the following syntax:

Public Declare Function RegOpenKey Lib "advapi32.dll" _
Alias "RegOpenKeyA" (ByVal hKey As Long, _
ByVal lpSubKey As String, phkResult As Long) As Long

The equivalent API call in C#, using platform invocation (p/invoke) is:

extern public static int RegOpenKey(
IntPtr hKey,  string lpSubKey,  out IntPtr phkResult);

Even though the upgrade companion performs the conversion automatically, there are times when the protoype of the function may be slightly off. This happens mostly because of the changes in the data types between VB6 and C#. One example is when a string is sent to a method and its contents are modified in the call. String management is always tricky, and, in those cases, chances are that the VB Upgrade Companion will convert the VB6 fixed length string to a System.String object in C#. The correct conversion would be a System.StringBuilder object – remember that Strings are inmutable in C#, but StringBuilders are not, and they can be marshalled to the API as the strings that need to be modified.

If you ever have a doubt regarding the prototype of a Win32 API function in C#, I recommend that you check out PINVOKE.NET. This website contains the P/Invoke signatures for most methods of the API, classified by DLL. It is very complete, and can definitely save you lots of time if you are having problems with a particular methods.

If you are new to p/invoke, I also recommend that you check out this MSDN article on the subject.