1

I have the c++ source code of functionality which is appealing to me.

What effort/work is involved/required in order to either reference this from a .net application or build this code as a .net assembly (preferably c#)?

This is my first attempt at porting code, so please breakdown your answer for me step by step.

durron597
  • 31,968
  • 17
  • 99
  • 158
c0D3l0g1c
  • 3,020
  • 5
  • 33
  • 71
  • Put it into a DLL and P/Invoke it. – chris Jan 04 '13 at 06:26
  • 1
    i've never used the .NET support of Visual C++, but as I understand it you can just create a .NET class that internally uses native code, completely seamlessly and with about 0 effort (this also avoids having to use explicit p/invoke from e.g. c#). if i had the time i'd fire up visual studio and just *try* it. have you tried it? – Cheers and hth. - Alf Jan 04 '13 at 06:30
  • @Cheersandhth.-Alf, As far as I know, that's the case with C++/CLI. – chris Jan 04 '13 at 06:32

2 Answers2

5

There are several ways of doing it.

  1. PInvoke
  2. Create C++/CLI wrapper around your C++ native code (make static library out of C++ native code) and C++/CLI generated assembly can be easily utilized in .net application.
  3. COM, i.e using interop (which is difficult among all the options)

In my suggestion easiest way is to use option 2, but you need to take care of proper marshaling.

Pranit P Kothari
  • 326
  • 3
  • 11
  • Just one comment - p invoke gets NASTY to deal with if you want oo-based class usage without COM. Heavily recommend CLI C ++ wrapper in that case. – JerKimball Jan 04 '13 at 06:46
  • 1
    Is there an application available that automatically P/Invokes all available methods in a given C++ dll? – c0D3l0g1c Jan 04 '13 at 06:50
  • c0D3I0g1c, this is actually a good question.. please let us know link or answer if you post it on stackoverflow. – Pranit P Kothari Jan 04 '13 at 07:06
  • @c0D3l0g1c: How would it figure out the arguments needed? – MSalters Jan 04 '13 at 08:42
  • One possible solution is a regex that identifies methods along with there parameters in a given c++ class. The results can then be used to build a c# class with P/Invoke method calls. – c0D3l0g1c Jan 04 '13 at 09:33
  • See if this helps.. http://coolthingoftheday.blogspot.in/2008/03/pinvoke-tool-you-been-looking-for-all.html – Pranit P Kothari Jan 07 '13 at 10:28
3

Solution A:

  1. If you have the source code, then compile the CPP program as a DLL file.
  2. Use P/Invoke

Solution B (if the functionality you want is in a static library):

  1. Create a stub function caller and compile THAT as a DLL
  2. Same as solution A.2
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • Is there an application available that automatically P/Invokes all available methods in a given C++ dll? – c0D3l0g1c Jan 04 '13 at 06:50