Build native c++ for use as .net library
Asked Answered
A

2

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.

Alexisaley answered 4/1, 2013 at 6:25 Comment(3)
Put it into a DLL and P/Invoke it.Hub
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?Trull
@Cheersandhth.-Alf, As far as I know, that's the case with C++/CLI.Hub
E
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.

Evite answered 4/1, 2013 at 6:32 Comment(6)
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.Ribeiro
Is there an application available that automatically P/Invokes all available methods in a given C++ dll?Alexisaley
c0D3I0g1c, this is actually a good question.. please let us know link or answer if you post it on stackoverflow.Evite
@c0D3l0g1c: How would it figure out the arguments needed?Frisse
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.Alexisaley
See if this helps.. coolthingoftheday.blogspot.in/2008/03/…Evite
H
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
Holography answered 4/1, 2013 at 6:30 Comment(1)
Is there an application available that automatically P/Invokes all available methods in a given C++ dll?Alexisaley

© 2022 - 2024 — McMap. All rights reserved.