Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and C++ Library

  • 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...

like image 636
Betamoo Avatar asked May 23 '10 15:05

Betamoo


2 Answers

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.

like image 169
Hans Passant Avatar answered Sep 29 '22 23:09

Hans Passant


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...

like image 32
Richard Avatar answered Sep 29 '22 23:09

Richard