s-s
s-s

Reputation: 380

DllImport from c# project to c++ project in same solution

I have a solution with two projects:

I need to call the C++ DLL from the C# project, using DllImport. When I provide the full path of the DLL, the application finds it. But I want to replace the path with a relative path, and I can't figure out how to do it.

Upvotes: 0

Views: 408

Answers (1)

Timo
Timo

Reputation: 9835

First of all, make the C++ project a dependency of the C# project. This ensures that the C++ project will be built before the C# project if it's outdated. You can set the project dependencies in the solution settings.

Now that we ensured that the dll is always up to date, we have to somehow get it in the same directoy as the C# executable. We have two options:

  1. a post build command to copy the dll to the output directory of the C# project, or
  2. we set the output directory of both projects to the same directory.

Post build event

We can simply use a copy command. Go to C++ project settings > Build Events > Post-Build Event and copy the following command to to the Command Line field:

xcopy /y "$(OutDir)*.dll" "$(SolutionDir)MY_CSHARP_PROJECT_NAME\bin\$(Platform)\$(Configuration)"

Replace MY_CSHARP_PROJECT_NAME with the name of your C# project. I'm using the default paths here, depending on your solution you might have to tweak the paths a bit.

Shared build directory

I wouldn't recommend this one, because you can run into trouble with it.

  1. Go to the Build tab in the project settings of your C# project.
  2. At the top of the page select Debug as configuration.
  3. At the bottom of the page change Output path to match the C++ output directory for Debug builds (this one is usually in the same folder as the solution file).
  4. Repeat 2 and 3 but this time with Release instead of Debug.

Upvotes: 1

Related Questions