简体   繁体   中英

C# Wrapper Around Unmanaged C++

I see that there have been similar questions asked here regarding wrapping unmanaged C++ with C# but they all seem to be about specific implementation issues. I'd like to know what the general approach is when using C# and unmanaged C++.

For example, I have quite a few classes written in unmanaged C++ that I want to be able to use through .NET (ideally with VBA in Excel). I've been using managed C++/CLI to do this so far, however have noticed some oddities with the language that I'd rather avoid. Reading further it seems as though I could wrap my unmanaged C++ in C# and then have direct access to .NET (while completely avoiding managed C++/CLI). Is this possible and if so what's the best way to go about it? Thank you for the help.

You have three choices:

  • Use a C++/CLI wrapper. The ideal solution if you're targeting .NET. You can access everything from the .NET world. You can wrap your C++ library with it, and then use it from C#/whatever.
  • Ditch .NET, and make a COM wrapper, possibly with the help of ATL. It is a little more difficult, but you can call your code more easily from VBA/Excel. You'll still be able to call your COM classes from .NET if you want.
  • Compile your code as a native DLL and use P/Invoke from C#. Note that this solution is tedious at best since nothing is automatic.

If your goal is really Excel/VBA, since you're going to make COM objects anyway, I'd go with option 2 and make COM classes directly using ATL. This bypasses .NET completely though, but using .NET to interface between C++ code and Excel has always been a hassle for me.

If you're wanting to avoid C++/CLI completely and use pure C# to access your native code, then it would have to be through direct P/Invoke, method by method. This is almost certainly not ideal if you have a large amount of unmanaged code.

Personally, I would think the "best" solution would be to continue using C++/CLI to write managed wrappers around your native code that expose the simplest possible public interfaces to reduce the complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM