4
votes

I am using Visual Studio 2008 Professional, and I need to create solution with two projects. One project is managed WinForms C# project, second is unmanaged DLL C++ project.

I created them in VS2008 and in unmanaged DLL project I exported simple function which returns some int. In managed WinForms project I imported DLL in a usual way and tried to print returned value in label:

[DllImport("DllProj.dll", EntryPoint = "GetSomeInt", SetLastError = true)]
private static extern int GetSomeInt();

But when I build solution and run, I get DllNotFoundException. I also tried to add an existing item(DllProj.dll) to WinForms project, but it only copied that dll from its Debug folder to folder with WinForms project, but not in Debug subfolder, where the compiled project resides. So I am still getting DllNotFoundException.

I also tried to add it as a reference, but VS2008 complains that my DLL is not COM or managed object. Is there some way to configure solution in such way that I don't need to manually copy the compiled DLL to Debug subfolder of WinForms project after each build?

3

3 Answers

6
votes

You should add dll copy to post build event.

See Project properties>Build events>Post build event command line.

2
votes
  • Copy the compiled dll to WinForms project after each build
  • Right click on the dll (which resides in WinForms project), click properties
  • Set "Copy to Output Directory" to "Copy if newer"
2
votes

DllImport is the right way to consume the unmanaged dll, since the c++ project is unmanaged you cannot add it as referemce in the c# windowsforms application and you have to copy manually or with a postbuild event the c++ dll used by DllImport to the bin folder of your managed app.