Using a C ++ DLL in a C # Application

I have an unmanaged C ++ DLL that just exports a single class (and not COM ... it's just a C ++ class) as its interface. I want to use this class in C #, but I was told that it cannot be simply imported into C #.

What is the correct way to use this class in my C # application?

+42
c # dll c ++ - cli unmanaged
Feb 20 '09 at 13:44
source share
5 answers

A simple way involving the Foo class:

  • Create a C ++ / CLI project, call this FooWrapper.
  • Make FooWrapper depend on an unmanaged dll (as you usually did).
  • Create a ManagedFoo managed class that contains one private instance field of type Foo *.
  • provide general transfer functions in ManagedFoo, which are sent to the primary instance field.
  • Optional (although recommended):
    • convert parameters from .net idioms (strings, etc.) to C ++ idioms (std :: string or char *)
    • catch unmanaged exceptions and throw managed ones instead

Then you make your C # code dependent on the FooWrapper / dll project and make sure that unmanaged ll is correctly deployed with it, how this is done depends on the unmanaged dll, but usually in the same directory.

If functions do not rely on instances of the class, then it is even simpler P / Invoke

+43
Feb 20 '09 at 13:53
source share

This answer may be redundant for one class library, but SWIG is a good solution for wrapping C / C ++ classes for use with other languages. It works well with C #.

Cm. http://www.swig.org/ .

+8
Feb 20 '09 at 14:24
source share

DllImport is your best bet. There are tons of data arrays, especially if you pass structures, but you can do anything with it.

+3
Feb 20 '09 at 15:18
source share

To overcome the managed / unmanaged border, you need a proxy mediator (GoF pattern).

Two options:

  • C ++ / CLI wrapper
  • Shell COM.

The first will be more direct, and the second pure C ++ → COM → .NET.

+2
Feb 20 '09 at 13:55
source share

It is sometimes easier to provide your own C. interface. SWIG is not trivial to configure. I use managed C ++ and C ++ / CLI and they are fine. The simplest is to simply make the C shell (and can be used by any other language, since most of them have a way to call the C function).

+2
Feb 20 '09 at 21:01
source share



All Articles