WaffleSouffle WaffleSouffle -4 years ago 178
C# Question

How do I add a reference to an unmanaged C++ project called by a C# project?

One solution (the.sln)

One C++ project (mycppproject.vcxproj in 2010or mycppproject.vcproj in 2008) which compiles a native DLL exporting some function(s). In debug this builds c:\output\Debug\mycppproject_d.dll and in release this builds c:\output\Release\mycppproject.dll.

One C# console application (mycsharpconsole.csproj) containing PInvoke calls into the DLL.

All compiles fine.

When I build, I would like to be able to add a reference from the csharp project to the cpp DLL project so that it can copy the appropriate file from the appropriate directory into the \bin\Debug directory the csharp project is built into.

This should be possible, since the IDE knows everything there is to know about where the DLL gets built, and where the C# application gets built.

In Visual Studio 2010:

I've tried "Dependencies..." on the csharp project and adding a dependency on mycppproject, but that has no effect.

I've tried "Add Reference..." on the csharp project and adding a reference to the cpp project, but I get a warning message 'The Target Framework version for the project "mycppproject" is higher than the current project Target Framework version. Would you like to add this reference to your project anyway?' (Yes/No/Cancel).

Clicking "Yes" produces the error message "A reference to mycppproject" could not be added."

Answer Source

I would follow Slaks' second answer...

[...] you can add a link to the unmanaged DLL as a file in the C# project, and set Build Action to None and Copy to Output Directory to Copy If Newer.

... followed by my comment, to differentiate between Debug and Release builds (even if is a little bit "hackish", since it requires you to manually edit the C# project file)

open your C# project's csproj file with a text editor and search for all "YourNativeCppProject.dll" occurrences (without the ".dll" subfix, so if you added pdb files as a link too, you'll find more than one occurrence), and change the Include path using macros, for example: Include="$(SolutionDir)$(ConfigurationName)\YourNativeCppProject.dll

PS: if you look at the properties (F4), VS shows you the Debug's path even if you switch to the Release configuration, but if you compile, you'll see that the dll copied to output is the release version*

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download