1

I have a C# Class Library Project in Visual Studio 2015 that creates a C# DLL. I use this plugin for various Unity Projects.

There are some math related functions that I have written in Native C++, which I want to access in my above mentioned Class Library Project. Is it possible to create a C++ plugin for the Class Library Project, which will finally be built into the C# DLL?

If not, what are other ways to use C++ code inside a C# Class Library Project?


@Jonathon Reinhart, I do not think this is a duplicate because in your provided link the user is trying to use C++ in a C# executable project. I am trying to create a C# DLL that uses a C++ DLL and is trying to ask if this was possible, and how to do it.

Taylor
  • 286
  • 4
  • 18
  • Native C++ or C++ .NET? One will produce a old native dll. The other a .NET DLL. Massive differences in using either. – Christopher Nov 06 '18 at 20:54
  • Native. I have edited the post. I am wondering if I can add a native dll into a class library project that will eventually create a c# dll. – Taylor Nov 06 '18 at 20:58

1 Answers1

5

There are 3 ways to use any existing DLL in any .NET Programm. In order of descending preference:

.NET DLL's can just be added to the project references. Indeed .NET executeables can be added the same. The internal structure is very similar to a .NET DLL. This behavior is comparable to Java bytecode adn executeables.

COM Interop. COM is bit of a predecessor for .NET. Not only can you use COM stuff in .NET, .NET DLL's carry COM interface stuff with them by default. Of course using this opens you to all the additional issues of using COM. It was a predecessors for a reason.

P/Invoke. The plusside is that you can use any old native DLL or Windows API. THe downside is that you work with all the limits of them. Unfitting binarities will get in the way. And often the best solution is to wrap the native DLL's into a helper process and use Interprocess Communicaation to talk with it.

So you get to pick your poision: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interop/

Christopher
  • 9,634
  • 2
  • 17
  • 31