Search code examples
c#c++importporting

How can I automatically reference a C++ DLL when using a C# class library in another project?


This is my first time using C++ dll. I have created a C# class library project that uses a C++ dll. After Googling, I ported the cpp dll using 'DllImport'

I built the project and confirmed that the 'UsingCppDllProject.dll' and 'A_Cpp.dll' files were copied in 'UsingCppDllProject\bin\Release' folder.

This is my Problem.

I need to use 'UsingCppDllProject.dll' in another project file. I referenced 'UsingCppDllProject.dll' which in 'UsingCppDllProject\bin\Release' folder. However, 'A_Cpp.dll' could not be referenced. How to solve it?

---------------------Here's what I tried:---------------------

I have finished porting the C++ DLL for use. My C++ DLL is placed in "UsingCppDllProject\UsingCppDllProject\Ref_Cpp". So, I set the dllName to "Ref_Cpp//A_Cpp.dll".

namespace UsingCppDllProject
{
    public class MyPortingClass
    {
        private const string dllName = "Ref_Cpp//A_Cpp.dll";

        public MyPortingClass()
        {

        }

        public int Do_AddFunction(int num1, int num2)
        {
            return AddNumber(num1, num2);
        }

        #region Porting
        [DllImport(dllName)]
        private static extern int AddNumber(int firstNum, int secondNum);
        #endregion
    }
}

I created a new project. Then, I referenced the 'UsingCppDllProject.dll'. When I ran the program, an exception occurred saying it couldn't find the 'A_Cpp.dll'. How can I fix this?

I think the simplest way is to directly place the 'A_Cpp.dll' file in the same location as the '.exe' file of the new project. But it seems strange to repeat this task every time I create a new project.

public class UserClass
    {
        private MyPortingClass tempClass;

        public UserClass()
        {
             tempClass = new MyPortingClass();
        }
        public void DoingAdd()
        {
            tempClass.Do_AddFunction(100, 400);
        }

    }

Solution

  • You should not reference dll files. You reference projects. I would suggest:

    Add A_Cpp.dll' to UsingCppDllProject` (add\existing file...). Open the properties for the file and chose

    1. Build action:"None"
    2. Copy to output directory: "Copy if newer"

    This should ensure the file is copied to the output directory of UsingCppDllProject

    Then add a project reference from your exe-project to UsingCppDllProject. This should ensure that A_Cpp.dll is copied to the output folder of your exe.