Code Focused

5 Tips for Developing with 64-Bit Windows

64-bit-capable machines are everywhere. It's time you start thinking about 64-bit support as you develop your Visual Basic applications.

There was a time when 64-bit computing was an exotic idea, but those days are long past. 64-bit-capable clients and servers-which have the ability to accept copious amounts of RAM and to run 64-bit versions of Windows-are everywhere. Video editing, graphics, 3-D modeling and data-intensive applications are just a few examples of software that benefit from 64-bit operating systems and hardware.

Whether or not your application or components need the extra addressable memory afforded by 64-bit architectures, you still want to be able to use your app on 64-bit versions of Windows. Here are five tips to help you develop applications with 64-bit Windows in mind.

1. Beat Bad Image Exceptions
All too often, developers run into this: "An unhandled exception of type 'System.BadImageFormatException' occurred." If you dig into the detail of those exceptions you'll probably find further information that says: "An attempt was made to load a program with an incorrect format."

This problem occurs because a 64-bit process tries to load a 32-bit assembly or vice versa. Although you can run both 64-bit and 32-bit processes on Windows x64, 64-bit code and 32-bit code can't run in the same process. Your code needs to be all 64-bit or all 32-bit. This includes any assemblies you load.

Visual Studio (VS) 2005 along with .NET 2.0 brought in the option to compile .NET apps to 32-bit (x86) or 64-bit (x64 or Itanium), as well as an option to set the output to "Any CPU." "Any CPU" is the default platform. If an assembly is compiled with "Any CPU" as the platform, then it will run as 32-bit or 64-bit depending on the process that loads it. With "Any CPU," the same assembly can run as 32-bit or 64-bit on 64-bit Windows: it's not really the CPU or OS that dictates 64-bit or not, it's the calling process.

To solve the bad image exception problems, change the target platform on all your assemblies to "Any CPU." If for some reason you aren't able to do that-perhaps an assembly is supplied without source-then set all your assemblies to the same platform, either x86 or x64. If you have .NET 1.0 or 1.1 assemblies, it's best to recompile them with .NET 2.0. If you can't recompile the .NET 1.0 or 1.1 assemblies, then compile your other code set to the x86 platform so that it is compatible.

Be aware that in VS 2005 and 2008, if you're using the "Visual Basic Development Settings" profile, changing the platform is a little messy. The problem probably stems from feedback the VB team got about how folks found all the different settings in Visual Studio disorientating compared to VB6. The result was that VB in Visual Studio was dumbed down almost to the point that it's as limiting as the Make dialogue was in VB6.

The good news is that you can take control of this. The simplest fix to give you ease of access to the build and platform configurations is to adopt the "General Development Settings" instead of the "Visual Basic Development Settings." Alternatively, change the "Project and Solutions" options from the Tools ... Options menu, ensuring that the "Show advanced build configurations" option is selected. Next, customize one of your toolbars so that it includes the "Solution Configurations" and "Solution Platforms" drop-down combo boxes.

Once you have these enabled, you can select the "Configuration Manager" from either the "Solution Configurations" or "Solution Platforms" combo-box lists. Doing so brings up the Configuration Manager window, where you can add or modify your configurations. Configurations allow you to do special builds, such as for testing, or force only some of the projects in a multi-project solution to be built. For each configuration you can also support different platforms.

To add either an x86 or x64 platform from the "Active Solution Platform" list in Configuration Manager, select "<New...>" and then select either x86 or x64 and copy the settings from "Any CPU." Later you can edit these settings for each individual project, using the project properties compile tab and advanced compile dialogue. If you aren't already familiar with build configurations, have a look in the VS help documentation for "Build Configurations," "Build Platforms" and "Configuration Manager Dialog Box." Build Configurations will make your development experience a lot better.

2. Size Matters
An important difference between 64-bit and 32-bit Windows is the size of handles: they will be different. If you have any Windows API calls in your code, you need to ensure your declarations are correct for 64-bit Windows. If your code was upgraded from VB6, you won't have any concept of difference between a handle and a 32-bit integer, so you'll have to look for the original documentation or header files. Identify which parameters and fields are handles, and use IntPtr for their types. Typically the documentation will identify these as INT_PTR or LONG_PTR or use a name indicating a handle of some sort, such as HWND. Parameters that are defined with prefixes such as PTR or LPTR are usually pointers and hence either have to be treated as an IntPtr or use ByRef marshalling. To determine if you're running as 64-bit base or 32-bit, you can check the IntPtr.Size value at runtime.

3. Yes Virginia, COM Can Be 64-Bit
A common misconception is that COM and ActiveX are limited to 32-bit, but with VB.NET you can use 64-bit COM and ActiveX controls. Few 64-bit compiled controls ship with Windows, but one notable exception is the sysmon.ocx ActiveX control, which lets you create system monitor graphs. My Vista developer machine shows half a dozen or so 64-bit ActiveX controls in the Windows System directory.

You can use the 64-bit ActiveX controls in a Windows.Forms application, but there's a catch when it comes to compiling. Visual Studio is currently a 32-bit app and it looks for the 32-bit ActiveX control at compile time to create the runtime callable wrapper for the COM component. To compile in VS you need to have the 32-bit version present. Once the app is compiled, only the version for the chosen platform is needed.

In the case where you either don't have the 32-bit version or the signatures for the 32-bit version are different from those of the 64-bit version, you can use the command line to run the 64-bit tools to create an interop assembly for the ActiveX control. See the documentation for TlbImp.exe for further details.

4. Beware of Broken Mirrors
When a 32-bit application runs in Windows 64, it runs with an emulator. The emulator is called WOW64, and is an abbreviation for "Windows On Windows64" and allows 32-bit applications to view their world as if it were a 32-bit operating system. The WOW64 emulator loads an x86 version of ntdll.dll, provides entry points and thunking (mainly for Itanium), and most importantly intercepts some registry and file system operations.

The WOW64 emulator also exposes different environmental variables to 32-bit applications compared to what the 64-bit applications see. Consequently, 32-bit applications see the ProgramFiles environmental variable as ProgramFiles(x86). If you write code such as MsgBox(Environ("ProgramFiles")), you will get by default "C:\Program Files" when running as 64-bit and "C:\Program Files (x86)" when running as 32-bit.

The emulator does similar things with the registry and the system directories. For compatibility and performance reasons, the %windir%\System32 folder is actually the 64-bit folder. That is, 64-bit applications do not have any emulation interception. The redirected folder for 32-bit operation is by default named %windir%\SysWOW64. The name SysWOW64 indicates it is used by the 32-bit emulator, WOW64. It can be a bit confusing.

The registry under WOW64 uses a combination of redirection and reflecting. The redirection resides under keys such as HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node. At least the naming pattern in the registry is a little better. The reflection is so 32-bit processes and 64-bit processes can both edit common keys such as file associations. On the other hand, the redirection is to ensure proper isolation of 32-bit from 64-bit.

The key thing is the implementation shouldn't matter to you unless you're trying to get details for a 32-bit app from a 64-bit app or vice versa. Usually it's far simpler to compile to the same target. For example, if you want to work with VS, compile your app targeting x86, and you won't need to worry about the file or registry emulation. If you run your app as "Any CPU," then depending on how it's launched, you may have to work with the redirection, and API calls such as GetSystemWow64Directory and use RegOpenKeyEx API for registry including the access mask of KEY_WOW64_32KEY. It can get messy and complicates testing. It's far preferable to compile to the same platform as the app and information you're targeting.

One complication I stumbled across was a combination of the registry reflection and the Windows Vista User Access Control (UAC). I was opening a key in the HKLM hive for write permissions, and the API was succeeding, yet when I went to write to the key it would fail. My application was running as 32-bit on Windows 64 and hence the key in question was being reflected. I wasted a lot of time trying to determine what was happening because the registry API was not behaving as it normally does. In the end I managed to get it working correctly by including a manifest with my application. Even though the requestedExecutionLevel had the level set to asInvoker, that was all that was needed to remove this strange combination of a bug.

UAC provides registry virtualization, and I think the combination of WOW64 redirection or reflection and UAC virtualization was too much. I now always ensure I have a manifest on my apps. In VS 2008 you can get to the manifest from the Application tab in the Project Properties dialog box. Make sure you include a requestedExecutionLevel option.

5. Enable Edit and Continue
Although you can debug a 64-bit app, you can't use Edit and Continue while debugging. This means you can't change the source code while debugging, instead you have to stop, apply the changes, recompile and start debugging again. You can, however, use Edit and Continue with a 32-bit app even if run on 64-bit Windows. This is another example where build configurations come in handy.

Create an x86 build configuration, and use that while developing so you can use use Edit and Continue. Then switch configurations to x64 or "Any CPU" for testing or nightly builds.

Working with either Windows 32 or Windows 64 isn't that difficult in VB8 (in VS 2005) or VB9 (in VS 2008). Use the power of Visual Studio and build configurations and the task becomes reasonably painless. This is a welcome contrast to the difficulties faced when porting earlier VB applications from 16-bit Windows to 32-bit Windows. The basis of .NET-abstracting you from the underlying operating system-makes this transition a relatively smooth one.

About the Author

Bill McCarthy is an independent consultant based in Australia and is one of the foremost .NET language experts specializing in Visual Basic. He has been a Microsoft MVP for VB for the last nine years and sat in on internal development reviews with the Visual Basic team for the last five years where he helped to steer the languageā€™s future direction. These days he writes his thoughts about language direction on his blog at http://msmvps.com/bill.

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube