1

I'm noob in C# and I already searched on the web. Anyway I'm still not sure about this and I do not have the total control of the code I have to implement, this is why I would like to be sure I needn't make any dll. I have a C++ file with a method, and I want to call this method from C# code. I just added "extern C" to the function.

When I just add the .h and .cpp files to the C# project they aren't detected. And of course, when I try to add it as reference, it doesn't work.

So do I absolutly have to make a dll ?

Mr. Starck
  • 232
  • 6
  • 16

3 Answers3

5

Your options for accessing the C++ code from C#:

  • Compile C++ as unmanaged DLL and access using p/invoke. This requires the C++ code be exposed using a C style API.
  • Compile C++ as unmanaged DLL and access using COM. This requires that you wrap your C++ in as COM objects.
  • Compile C++ as mixed/mode C++/CLI assembly and access the assembly as a managed reference. This requires that you wrap the original C++ as managed C++ ref classes.

All of these options, by necessity, involve the creation of another module/assembly. You cannot link the C++ code directly into your C# assembly.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    Might be worth clarifying that the first option really only works when calling a C API, and the second option requires your C++ code to be written as COM object(s) – jalf Jan 10 '14 at 09:44
  • @jalf I've added words to those effects for all options – David Heffernan Jan 10 '14 at 09:52
0

You might like to try using the PInvoke Interop Assistant to generate the C# necessary to interact with the DLL via Platform Invoke. Be aware that this is imperfect though so YMMV.

Another alternative, if you have the knowledge and patience, is to make a COM component out of your native C++ DLL and consume that from C# by using the Type Library Importer to create a managed wrapper.

Roger Rowland
  • 25,885
  • 11
  • 72
  • 113
0

You won't be able to interact with .cpp/.h files since you need at least a binary object (assembly) for C# to interact with and C# won't generate any binaries from .cpp/.h. That's on the subject about adding these files as references to the project.

As for the argument that you don't have control over the code - well, don't make a DLL out of the actual .cpp/.h, but make your own thin DLL that has a wrapper object that just includes the headers, calls whatever method you would be calling and links to the appropriate .o files or .lib or whatever you have. If the interface changes you would just changed your thing wrapper which should be easy.

Rudolfs Bundulis
  • 11,636
  • 6
  • 33
  • 71