How should I write my lib in C++ for use in .NET?
I have a prototype for a lib written in C++. It is CPU intensive so I wrote one part in C (because of tools) the meat in C++ and used custom memory allocators and various things.
I would like to use this lib in .NET. I'm not exactly sure how I should do it. It seems like I should either write a C interface and write a wrapper in .NET to 开发者_StackOverflow社区use managed C++ which I am assuming I have the exact same code files except I add a file or two and write a managed class for them.
What are the benefits or restrictions I should know about if I go the managed route?
C++/CLI is the answer you're looking for. The beauty of C++/CLI is that it allows you to mix native C++ with .NET code, which you can use to build a library for consumption by .NET developers. The following MSDN article is a great introduction to how it works:
http://msdn.microsoft.com/en-us/magazine/cc163852.aspx
Hope this helps!
It depends on the "surface contact" between your C++ library and your .NET code (BTW, you'll need to expose it as a DLL whatever way you choose)
If you really have a fully object oriented library with classes, methods, properties, i.e: an object model, you can go for the C++/CLI, so the integration will be quite transparent. The drawback is you'll have to understand some of its subtleties (and I think you also have some constraints about how you'll embed the MSVC runtime).
If you can reduce the API to a finite set of methods, than you can just export some of these methods and use P/Invoke (DllImport attribute. See this tutorial here: Platform Invoke Tutorial). In this case, make sure the exposed parameters will be consumable by the .NET layer (don't use complex C/C++ types, pointers to pointers to pointers, ..., don't use C++ classes, ...), and try to ensure memory allocation will be done by the .NET side.
PS: as a side note, you should think about the 32-bit / 64-bit issue. Will you DLL be available in 64-bit? Will you distribute both version? .NET is capable of both.
精彩评论