How can I add a VC++ DLL as a reference in my C# V

2020-07-18 04:41发布

问题:

I want to add a VC++ DLL reference into my C# Visual Studio project. But when I try to add it I see, "It is not a valid assembly or COM component".

Please suggest how I can use the VC++ DLL as a reference in a C# project.

回答1:

There are two options for using a C++ DLL from C#: either COM interop, or P/Invoke. COM Interop involves creating a COM object in your C++ DLL, and then adding it as a reference. You can use the COM object like a C# object (for the most part) at this point.

P/Invoke allows you to call exported functions from C# (think calling standard Win32 API functions from C#). This is likely easier to set up, since all you need to do is export a function, however that could cause you to refactor your code in the C++ DLL, since it's not a very OOP way of doing things.



回答2:

You can only use C++ components in C# when they have been prepared for use, for example by being written in C++/CLI or being written as a COM server.

If your component is a plain C++ dll you'll need to write some wrapper code, probably best is C++/Cli



回答3:

I am not sure whether this solve..

run:

tlbimp /out:MyOldCom.dll MyNewAssembly.tlb

Then use it as you would any other assembly.

Please refer

http://msdn.microsoft.com/en-us/library/aa302324.aspx

http://msdn.microsoft.com/en-us/magazine/cc301501.aspx

ie)

One way is to package your DLL as a COM class and Another way is using DllImport