-1

I have a DLL which can be used with no problems in a Visual C++ project. When I take the same DLL to be used in a Visual C# project, there are problems.

For the Visual C++ case, all I need to do is to place the dll in the same folder as the executable. For the Visual C# project, when I tried that, I get the error %1 is not a valid Win32 application. Then I tried to add the dll as a reference in the Visual C# project but failed. The error received was The dll could not be added. Please make sure file is accessible and it is a valid assembly or COM component.

Is this because the same dll that works on Visual C++ cannot be used in Visual C# project without modification?

Thanks. I am using Visual studio 2012.

guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • 1
    You may want to read on differences between managed and unmanaged code... Than read on PInvoke and "native interop". Than improve your question to make it clear how do you want to use your C++ DLL in C# project (as COM component, via PInvoke, some form of IPC...) – Alexei Levenkov Jul 31 '14 at 01:32
  • Why the negative point and the votes to close? It is not a vague question. Can a DLL that works for Visual C++ work for Visual C#? – guagay_wk Jul 31 '14 at 01:32
  • @Alexei Levenkov: thanks for pointing me in this direction. I know nuts about the things you mentioned. Will read up on them now. But does it mean the C++ DLL can be used in C# if it is called in C# correctly? – guagay_wk Jul 31 '14 at 01:34
  • 1
    Also it may be good idea to check out related questions when you post yours (like http://stackoverflow.com/questions/21866345/using-c-dll-made-from-eclipse-in-visual-studio-2012-c?rq=1) even if you don't know correct search terms. – Alexei Levenkov Jul 31 '14 at 01:34

1 Answers1

1

It can but there is a special way of doing it. First, the DLL must be in the same directory as your executable (C# Assembly) or at least in an appropriate DLL search path. Then you need to define every single call you want to make into the DLL using P/Invoke (as Alexei points out). Here is a tutorial provided by Microsoft on the subject.

Lets say you have a function inside your C++ DLL that is provided two integers, adds them together and returns the result. Below is a short application that call the function inside your C++ DLL.

using System.Runtime.InteropServices;

...

public class Program
{
    [DllImport("yourcppdll.dll")]
    public static extern int AddNumbers(int n1, int n2);

    static void Main(string[] args)
    {
        int result = AddNumbers(2, 2);

        //result equals 4
        Console.WriteLine("Result is " + result.ToString());
    }
}

There is much more you can do with this, this just happens to be a very simple example.

vane
  • 2,125
  • 1
  • 21
  • 40