开发者

Using C++ classes in .NET

I have a set of classes that I've written in C++ for a code base that will run in Linux commandline. They primarily use the STL and no fancy features of the language. They've been tested, and work.

I need to write a GUI app for the .NET framework that does things using logic I've written in those classes, but run on Windows. A critical requirement for the Win开发者_开发技巧dows app is that it behave exactly like the Linux app would. Hence, I'd like to share the code between the two code bases.

So, I'd like to import them (or so) into a new code base, and keep changes in sync between the two. Ideally, I'd like to write my .NET stuff in VB.NET, as I'm more familiar with that, but I'm willing to change to C# or C++ for .NET development.

My question is, how can I use those C++ classes (with minimal changes) in a .NET project? Is this even possible? Can I create a library or so in .NET?

NB: my .NET experience is limited, so I apologize if this is a newbie question.


Yes, you can - you can use C++ code (as long as it doesn't depend on Linux-specific functionality) in a .NET application. C++/CLI is a superset of C++, offering access to the .NET managed classes and other features. Take your existing code, build it as a DLL (managed if you can, unmanaged if not), then create the GUI parts that call into it.


You're probably not going to be able to simply port this into an equivalent C# library. You may want to consider managed C++ to create a referenced assembly which you can call. Alternatively, if you have a Windows DLL that houses this library, you can use Interop to call the code from your C# program.


If you have architected this well, so that your logic is in a relatively small number of functions that don't care about the GUI, then I suggest building the logic in a DLL you can call from your GUI.

One approach is to expose a bunch of "extern C" functions taking relatively simple parameter types (eg ints and strings rather than large structs-that-inherit-from-other-structs etc.) Then you can easily use P/Invoke (aka DllImport) to call that code directly from your VB.NET code. Meanwhile your Unix code can also call the same functions in the same code base. No forking.

If you need to pass more complicated parameter types, then you might want to write your UI in C++/CLI (because it can just inlude the header and know the types) or (since the designer story is quite sad for C++/CLI) write your UI in VB.NET and add a reference to a wrapper C++/CLI assembly that calls the logic. In either of these cases, the functions don't have to be "extern C" if that makes your life simpler.

Either way, do not copy all your business logic into a new VB.NET or C# or C++/CLI file and go forward maintaining forked code. You will be happier keeping a common core and interopping to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜