views:

139

answers:

2

I want to know what is the best approach to wrapping a massive library written in C++ to make it accessible in C#.

I have done work with interop before, and I love IJW. But I am not sure of how to implement this approach with a huge library. I am wondering if there is any pattern to use, otherwise I just have to write a wrapper around every class that exists in the c++ library which is not really manageable.

Also, I cannot just provide a single facade into the library, as again, it is very big, and overwhelming at this point, so any ideas would be greatly appreciated.

A: 

If performance is a top concern, stay IJW. If you have to write wrapper classes or prefer more readability in your code, I suggest you create COM wrappers as there are IDE wizard to help you on generating code and COM can also be used by native clients. That's how Microsoft expose their APIs for Office and IE.

Sheng Jiang 蒋晟
A: 

I've been through a process similar to what you describe. In our situation there was no easy way to wrap the classes (IJW isn't a workable solution for a large C++ library), so we did wrap every class.

We wrote a wrapper around first the core classes we needed to consume in our app and added wrappers for other classes as necessary. These things in particular helped us:

  • In our wrapper layer we made heavy use macros to translate translate between c++ code and .NET concepts. e.g., Macros were used to translate 'property' type methods into true .NET properties.
  • We always exposed the native C++ class as an IntPtr using "property IntPtr NativeObject { get(); }". This allowed us to split the wrapper into multiple components while still allowing the wrapper objects to pass native objects to one another.
  • A thorough nunit testsuite to verify everything worked as expected.

There is a lot of work involved, but writing a wrapper around every class is manageable, but (obviously) only worth while if you get sufficient benefit. Writing the wrapper "by hand" also gave us fine-grained control over the interop which was essential to the success of our project.

mcdave