- I was wondering if I can use a library -written in C++- in C#
- The probl开发者_Python百科em 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...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.
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...
Another option is to write a managed wrapper in C++/CLI. I prefer that instead of using P/Invoke.
精彩评论