Archive for Interop

Mixed C++ and C# Projects – Post Build Events

I suspect nobody at at Microsoft deals with projects which contain a mix of C++ and C# code (typically this might be a C++ DLL called from a C# .NET UI). If they did, they’d very quickly realise the stupidity of not copying the C++ project output into the C# project’s output directory.

You might expect that adding the C++ project to the C# project as a dependency would make it plain to the Visual Studio IDE that perhaps it really ought to consider ensuring the latest C++ DLL appears in teh C# project’s target directory. But no, it does nothing (and is why I’ve tagged this as a Visual Studio Bug).

You can of course create a post build event in the C# project to copy the C++ DLL into the target directory. But if you modify the C++ DLL, the C# project doesn’t think it needs to build, ergo, does not run build events. Understandable – but annoying.

One “fix” would be to have the C++ project, as part of its post build, write to a skeleton .cs file that does nothing but is part of the C# project. Then the C# project THINKS its been modified and runs its post build where you then copy the C++ DLL across.

Not brilliant.But the skeleton file will then have a later date/time than the last C# project build date time and the C# project will build again – very quickly too since almost nothing has changed.

But that suggested another solution of sorts. Create a file – any file – lets say a text file. Set its date/time to way into the future, like 2050 or something, make it write-protected and add it to the C# solution with the properties of “build action = none” and “do not copy” to output. The project now has a file that is always dated after the last build so always builds, always runs the post-build event in which you can always ensure the latest C++ DLL gets copied to the target directory.

With luck, the only thing you need to remember is to restore the file date/time whenever the text file is re-created when restoring from, say, subversion.