Setting up C++ Interop (with Win32) in VS 2005.

I've already given the steps necessary to make this happen in an earlier post, but as this will come up so much I decided to pull it into a seperate post with more explicit details.  The basic things you need again are:

  • /clr option set for the project.  (Common Language Runtime support property under General.)
  • Include the appropriate Win32 headers.  (#include <windows.h> is the main one)
  • Appropriate target OS #defines. (see Using the Windows Headers for the right values)
  • If the project was started from one of the CLR templates, you'll need to remove $(NoInherit) from the Additional Dependencies property under Linker:Input.

As mentioned in the earlier post, it's probably a good idea to put the Win32 #includes in a precompiled header for speedier compilation (stdafx.h typically, see Creating Precompiled Header Files for more info).  Here is what this looks like (for the latest versions):

// Target platform defines:

#ifndef WINVER
#define WINVER 0x0501

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501

#ifndef _WIN32_WINDOWS
#define _WIN32_WINDOWS 0x0410

#ifndef _WIN32_IE
#define _WIN32_IE 0x0500

// Disable warning for XML comments.
#pragma warning( disable : 4634 )

// Windows Header Files:
#include <windows.h>

#pragma warning( default : 4634 )

Ok, but what about the warning disable?  In Beta 2, turning on XML comments would cause parsing of all included headers as well.  Not really what you want given there are a number of places XML delimiters inadvertently show up (they aren't actual XML comments, so you are likely to get errors).  My last word was that in the final code includes that have the #include <header.h>   (as opposed to the #include "header.h" ) format will not be parsed to make this easier.

So... step-by-step:

  1. Create or load a project.
  2. Set the /clr switch.
  3. Ensure the dependencies property isn't set to $(NoInherit).
  4. Add the relevant Win32 #defines and #includes if needed (see above).
  5. Code. (See my other articles [1], [2] for more details.

That's basically it.  Some other useful links from MSDN: