views:

137

answers:

3
  • I was wondering if I can use a library -written in C++- in C#
  • The problem is that library has its own structures and classes.. Will I be able to use it in C#?

Thanks

EDIT
This library is open source..
so if my requirements needs something special in C++ code, I will be able do it...

+3  A: 

There are two ways, both using an Adapter (which maps C++ classes to .NET classes):

  • C++/CLI
  • COM

The former avoids going via COM, and much of the C++ code might be able to be just compiled with the correct switches.

Additional: In theory P/Invoke might be possible, but all the C++ semantics would be lost, you would need to handle C++ object lifetime manually (and instance references as IntPtr). Plus of course you would need to call the mangled names...

Richard
+3  A: 

Another option is to write a managed wrapper in C++/CLI. I prefer that instead of using P/Invoke.

Axel Gneiting
+3  A: 

You cannot directly use C++ classes in managed code. The chief problems are not being able to use the same memory allocator as used by the C++ code and not being able to invoke the constructor and destructor easily. A Microsoft employee posted a blog post to show that it is not impossible. I would not recommend doing this.

COM is a solution but that invariably requires a fairly big rewrite and good COM programming skillz. A managed class wrapper in the C++/CLI language is usually the best solution. You could take a peek at the SWIG tool to consider auto-generating those wrapper classes. Beware however that this tool can easily create more problems than it solves.

Hans Passant