Port unmanaged C++ project to C# - c#

I need to port a C/C++ unmanaged project (VS 2008) to C# (preferably .net 3.5).
Are there any conversion-helping
tools; let's say something
translating the code syntax and
asking you verifications/modifications for each
problematic point (I guess I'm dreaming...)
Where can I find some useful howtos or articles about this translation.
They would be very useful if they contained specific hints like:
extern variables should be set in public static classes
(I don't know, I'm guessing...)
Please no suggestion like "You can call your c++ dll from .net", because I know it's possible, but just I can't.
Note:
The C/C++ project uses only STL and
other basic functions, no 3rd Party
libraries etc.
I can't use it directly or wrapped
from C# because our company needs to
mantain/modify the code and we're extremely
more skilled in C# than in C++.

It will cost you far more to convert it than to wrap it and pay a freelancer (like me) to help you out by changing the C++ code for you every few months (or every few years) when you need to make a change. There are some mechanical approaches but the bigger issue is that you can never really be sure that the new C# code does exactly what the old C++ code did. I have clients who have tried this and most gave up and threw the work away. The ones who succeeded did it very slowly, like this:
First, you wrap the old library and get your UI or whatever the new code is (web service, whatever) successfully calling the old library. This gets everyone some "bang for the buck" and buys you time to solve the "we can't maintain our old code" problem. You also develop a comprehensive test suite that proves what the old library does for various edge cases and strange things that only happen in the wild every few years. Over time, you move functionality from the old library into a new C# one and change the calling code to use the new library for that functionality. You move the most volatile parts, the things you change most often, out first. At every stage you run the test cases again to make sure your translation from C++ to C# didn't mess up the results it calculates. Maybe some of it you never move out, maybe in the end it is all moved. You stop when you feel the risk of being unable to maintain your own library and needing to pay someone to do it for you has dropped below the cost of continuing to translate it.
I recommend you have access to someone with good C++ skills when you start. You will probably run into things that don't make much sense to you. But you can get the value from the library pretty quickly, and still solve your underlying problem in the long term.

Depends on what you mean by port.
You can rewrite some of the stuff in C#. Not everything. Some HW or legacy libraries would have to be handled with C/C++ even if you port your own code. I don't know of any reliable automatic converter for C++->C#, and I doubt one can exist.
A better idea may be to wrap your existing code in new C# code. You could create an interop layer in C++/CLI, for example. Or you can communicate with your native code with something like Google Protocol Buffers, if you don't want to mix native/managed code in the same process.

I doubt code conversion tools would help. If you need to make some C++ work in some fashion with .NET, the easiest way is to write a managed C++ layer that wraps it and provides an interface for .NET apps to work with. But it depends on the code.
What is the purpose of rewriting and what does your code do? Does it interface with other components? Does it have a GUI? Is it a standalone executable or a library? Is it a COM / ActiveX server or does it use COM components? Does it link to other DLLs or use 3rd party libraries?
All these affect how you're going to port / rewrite from scratch your app. For example, if your code is an MFC app you may as well forget trying to salvage much code. If your app does http / high level networking stuff you may as well write from scratch. If your code low level you might have to refactor with some C# and some C++ accessible through a managed C++ layer.
Lots of choices and it really depends what your app is doing, how it was written etc.

Related

Can a Delphi 4 and/or Delphi 5 executable be integrated into a C# application?

Can Delphi 4 and\or 5 application functionality (.exe) be integrated into a C# application?
I've been tasked with rewriting a new application which will be based off of existing Delphi 4/5 written application, which are currently held together with a Batch Processing Script that no one at my company understands.
As an interum solution, I've been asked to investigate whether a C# GUI\wrapper can be placed on top so it's easier to maintain and run.
I know that Delphi 6 applications can be called within a C# application using reflection but I'm not entirely sure how.
So back to my original question can a Delphi 4/5 application functionality be called within a C# application?
Thanks in advance.
The underlying premise of the question appears to be that a C# wrapper around a Delphi core is easier to maintain and run, and if that is not true, then the idea of creating the wrapper becomes not-very-useful. I believe it is a wrongly-conceived notion.
Imagine that I made an application that can talk to a telescope. It does it perfectly. In that case, I might be able to extract just the telescope-communication part and put it in a DLL and then write a user interface in C# that uses the Delphi DLL just to do the communicate-with-telescope task. However, unless your Delphi application was already structured in a nice way, and unless a task like this telescope-communications library already exists, you won't find it very easy to extract any part of a Delphi application, and use it from C#. If that situation existed, I would use native Delphi DLL function exports and invoke them from C#. This is not using the existing delphi executable, and requires many hours of work to refactor part of a Delphi application into something that could be used from C#.
Another answer mentions COM Servers, and while that is possible, it is not going to make things easier; Like the old joke about regular expressions; When you have a problem and try to solve it by using regular expressions, now you have two problems. The same becomes true when you try to use COM Servers to hide your existing application and write a whole new UI on top of it using C#. It would actually take more technical skill to improve, debug, and continue to develop it that way, than to keep developing it either purely in delphi or purely in C#. It's a negative savings of effort.
You have given no information about what the Delphi application does, but let's assume that it's a line-of-business or vertical market application that reads some file format, or does some communication protocol, or even connects to some old database, that you don't want to rewrite.
If by making the C# UI you mean, to never show the Delphi application user interface and replace it with a C# one, it is nearly certain that your idea is not going to make anything any better, and can only ever make things worse. Your deadlock either comes from not having skilled delphi developers, or else it comes from not having clever developers who can figure out what an existing application does.
The solution is usually a human solution when you are in this situation; either to hire a skilled delphi developer and bring the application forward into the modern Delphi era (Delphi XE2) or to hire a skilled non-delphi developer and port the application to some other language. Anybody who would suggest writing a "wrapper" over top of the delphi application who thinks that will make it "easier" obviously feels incapable of rewriting the existing application.
I don't know enough about what your delphi application does, to be sure, but it sure sounds to me like "fear driven" decisions. Wrapping old code is almost never a good idea, and is most often, just the creation of more problems.
A Delphi .exe can be run from C#. But I guess this is not your point.
You can either use a COM server, which is standard but needs the COM object to be registered on the computer (by running regsrv32.exe). Not so easy to deploy.
Or you can define the Delphi code as a library, then load and execute the .dll from the C# code.
If you prefer to access C# objects from Delphi 4 or 5 (that is access C# RTTI), you'll have to use some low-level unit like Managed extensions for VCL - .Net interop for Delphi Win32. Which is quite complete, and works with old versions of Delphi (whereas something more high-level than Hydra will not support Delphi 4 or 5, sadly).
Edit
Another possible easy communication is GDI messages. You can send GDI commands from your C# code to control the Delphi application, but using PostMessage() API calls.
Sure. C# can call any .exe. Just use Process.Start:
http://www.dotnetperls.com/process-start
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx
Delphi 5 supports implementing COM server functionality (don't know about earlier versions, D2 definitely did not).
If you have the sources available,
add a type library and a COM implementation of the interfaces defined in the type library,
register the executable (typically done automatically on startup thanks to Delphi magic)
follow the steps on MSDN: Exposing COM Components to the .NET Framework

What is the best way to port a C++ library to C#?

I have a (header only) C++ library that I am looking to port to C#. It is a wrapper of the win api which I have made for a certain purpose. I want to port it to C# because I want to develop it further using C#. What is the most efficient (and easiest?) way to port it. Please note that I do not want something hectic because I don't want to spend more time porting the library than it took to make that library in the first place. So is there a way?
It depends very much on how big your lib is, how it is structured, how your memory allocation looks like, how much you made use of libs not available in C# (like the C++ std lib), how much C++ template programming you have used etc.
Different strategies may be
try to port (parts of) it automatically by some code generator of your own
do not port it to C#, instead use C++/CLI (something I did very successfully in the past)
do it manually because the C++ concepts you have used so far don't map well to C#
"Header only" does not seem to make a real difference. In fact, things may technically get a little bit easier when you have just one C++ file for each class to be ported to one C# class file.
A couple of ways I can think of.
Manual conversion to C# dll with possible code generation help of T4.
Change your c++ library to a managed dll so you can use it in your c# project.
Of course, you might use interop with your c++ library in your C# project. But in that case, I am not sure about purpose of your c++ library since you said it's a wrapper.
Since you already have c++ library that you can fully control, I would try to go with #2 first.

Unmanaged C++ Win32 API or C#?

Good afternoon,
I thought about writing an application which I may or may not commercialize, depending on how good the final application is. It is like a personal project, with which I hope to learn many more things about programming, for currently I only know most about C and C#. That's why I thought about starting this project as an unmanaged C++ Win32 application. The problem is that it is most dificult to even show a simple window when compared to C#...
How many people/companies use the Win32 API & C++ in today's business world? How does it perform in comparison with C#?
The application in question may eventually be an IDE for a specific language but whith features like command recognition and spell checking already built in.
Thank you very much.
It seems that when performance is needed people are willing to give up C# for C++.
Have a look at this "success" story Lessons from Evernote’s flight from .NET.
On our test hardware, Evernote 4
starts five times faster, and uses
half the memory of Evernote 3.5.
Evernote chose WTL and Chromium Embedded Framework. Basically they've reused Google's Chrome in their application.
For your first project and w/o prior C++ and Win32 experience, I would STRONGLY recommend you use the C# , as it will be easier for you to get something done thereby gaining confidence and skill as you go.
I'm a huge fan of C++ under windows, I've been doing it most of my adult life. That said, if you have no experience of C++, and you want to write a windows application, I'd suggest going with the C# route under .NET. Whilst I love native C++, I really disliked C++/CLI, and the horrid ^ suffix for references.
Given this is a personal project, I wouldn't worry too much about whether businesses use C++ or C#, but I will say that it is easier to find a C# developer these days than it is a C++ developer. And no, I am not favouring one language over the other here, it just appears to be the reality (at least in my experience). As for C++/CLI developers? They're kind of thin on the ground :)
You'll definitely be up and running faster with C# than you would with Visual C++/MFC/some-other-gui, but remember there are certain things you may not be able to do in C# (and have to import the native win32 calls via DllImport), but I doubt you'll come across these fringe cases just yet.
C# is the easy route, and the route most-often pushed by Microsoft. What they don't tell you, though, is that all of their headline products (parts of Visual Studio excepted) are written in C/C++. I'd say, in fact, that most major software packages you are familiar with are written in C/C++.
I'd go with c# too, as it is far more common in a business world (on GUI side at least), than unmanaged c++/win32. You'll also get your desired results faster, especially if you don't know c++.
On the other hand, c++ performs better (if written properly) - so if you are planning some intensive work in your app - maybe c# just won't handle it (but I strongly doubt this is the case).
At last, but not the least - if you are planning for clients, that for some reason do not have and can not get .NET framework (or any other framework, i.e. Java) - then native code is your only solution.
I have only been using C++ for quite a few years, but I have never had to write any programs which required a User Interface. When I did, I tried to learn to use Qt, but found it to be somewhat of a pain and eventually gave up. I recently just started taking a class on C# .NET and in the first week I have already started developing a pretty advanced application for my companies billing system.
If you were already a seasoned C++ veteran and preferred it over C# .NET, then I would say by all means go for it. In this case however, I would strongly recommend you go with C# .NET for quite a few reasons.
1) The time is takes to do something in C# will probably be at the very least about 10x faster than doing it in C++ regardless of the API you used.
2) The learning curve of C++ on top of already trying to write an application with a UI (which is already very difficult in C++) will make this take an extremely long time.

Is C++ and .NET used together in Domains like Banking , Health Care and Telecom

Or I should ask how helpful and benifitial will it be to start with C++
This may seem irelevant but it has some significance for me,may be few others like me.
I just want to know ,How Important is it to Learn C++ , COM and ATL while you are a .NET programmer?
I love programming with .NET and C# .Visual Studio just has it's own charm of intellisence ,Color Coding and other pretty features , which make us addicted to it.
I was thinking , almost we can build anything with C# and still it holds true mostly, but it lags sometimes like:
While I try to create a Shell Extension , then it is highly suggested to use unmanaged code instead of any managed code.
Also there are few other things like COM , ATL , which are preferred to be coded in C++ rather than C#.
I am just 4 years in IT industry and love to be Solution Architect.
So need all your inputs to know , how important/helpful will it be in my future venture if I am doing my Current COM Project with C++ , which integrate with .NET UI.
Is there any implementation of C++ and .NET in common domains like Health Care, Banking and Telecommunication.
The issue (at least for the specific cases you mention, such as shell extensions) with trying to "integrate with a .NET UI" is that you really can't. The reason it's not a good idea to write shell extensions in managed code is that a given process can only load one version of the CLR at any given time. If two shell extensions depend on different versions of the CLR, and they both try to load at the same time, it will fail. You can't load the CLR in any way shape or form in the context of your shell extension and be a well behaved shell extension.
My advice would be to not bother with C++ until you really have a reason to learn it (despite that C++ is my favorite language). But when you do learn C++, leave your .NET baggage at the door. There are lots of things (such as excessive use of casting, constantly using new, etc) which are idiomatic C#, and are just plain wrong in C++. You will be a lot happier if you don't try to understand C++ concepts in terms of the CLR -- simply because C++ doesn't run there. You can use some of the design patterns you may have learned for C#, but how the underlying language and machine operates are completely different between the two languages.
Probably the most confusing difference for new C or C++ programmers is the concept of undefined behavior. The C and C++ standards are written in such a mannar as to not be tied to a particular machine. This is in stark contrast to architectures like Java or .NET, where the language is actually defined in terms of a virtual machine (and therefore is extremely dependent on that VM). This leads to places where the standard literally does not say what the correct output of a program should be; and instead says "however the underlying machine usually does this". You'll probably notice this quite a bit if you're ever dealing with floating point math. While C# has strict and specific rules about how and where floating points are calculated and rounded, C and C++ make no such qualifications.
Once you understand C++, then you can move on to COM and ATL. COM is essentially designed to make a C++ like class structure accessible in a language (the COM ABI), machine (marshalling between 32 bit and 64 processes on the same system, etc), and location (DCOM provides RPC facilities) independent way. If you don't understand the C++ object model, then you're going to have an extremely difficult time with the COM object model, because the two are extremely similar. ATL is a set of C++ class templates around COM fundamentals which simply handle some of the boilerplate for you.
I just want to know ,How Important is
it to Learn C++ , COM and ATL while
you are a .NET programmer?
Depends what you do. You are way better of learnin about databases. Pretty much every serious app uses a database.
But C++ IS ued together with .NET - especially C++/CLI (the managed variant) as it is very good for integrating C++ code with managed code effficiently. Quite often pretty much the only efficient way. Which is important if you for example raise events for market data. With a frequency in excess of 100.000 times. Per second.
But this is a NICHE. I work in the financial area, and tthe C++ uses AND integration uses are SMALL compared to the people working in .NET / In the application.

Effort estimation: using C / Win32 or learning C# / .NET

I intend to write a small application to scratch a personal itch and probably make the life of some colleagues easier. Here is what I have:
10+ years of experience in C
Plenty of experience in programming against the Win16/32 API in C from the Win3.1 to 2000 days.
C library written by myself already doing about 75% of what the application shall do.
What the application shall do:
open a binary, feed it into the mentioned library.
take the resulting text output and feed it into a new Excel Workbook.
apply some formating.
integrate nicely with the Windows environment (availability in "Open With...", remember some stuff using the registry etc.)
(maybe later) before giving the CSV data to Excel, parse it by looking up the meaning of some values in an XML file.
Except for the XML parsing part I have done all of that stuff before including COM / Office Automation in C/Win32. There is a lot of boilerplate code involved, but it is doable and the result will be a pretty small application without the need for an installer.
So why even think about C# / .Net?
no experience with parsing XML
the promise of less boilerplate code for the Windows and Excel stuff (yes, I have done C++ with OWL, MFC, ATL etc. but I am not going there anymore - not for free/fun)
Since I have also experience with C++, VB(not .Net) and a little Java / Objective-C I suppose learning C# will all be about the .Net libraries and not actually about the language.
My considerations so far:
Learning .NET might be fun and might result in less code / first steps in a more modern environment.
Sticking with what I know will lead to a predictable outcome in terms of effort and function (except for the optional XML stuff)
VB looked great at the beginning until the projects where about 80% done, then the pain started and the DLL coding in C. I am concerned history could repeat itself if I choose .Net.
My primary objective is the functionality. Effort is a concern. The XML parsing is optional.
Please advice.
Update: one thing I forgot to mention explicitly is that I am also worried about easy deployment of the tool to my co-workers. With Win32 I am pretty sure I can come up with an EXE file < 1Mb that can be easily emailed and does not require installation. With .Net not so much. Can I create the necessary MSI or whatever in Visual Studio Express (free) or do I need 3rd party tools?
as others have your question mostly covered, I'd just like to quickly comment on your considerations:
Learning .NET might be fun and might result in less code / first steps in a more modern environment.
Totally agreed. It is definitely fun and usually it does result in less code. The investment you make now will certainly benefit you in future projects. It is way faster to program in .Net than in C. Not only it is easier, but it is also safer. You are isolated from many programming errors common in C mostly related to memory mismanagement. You also get a very complete managed API to do stuff you would usually need to build your own framework.
Sticking with what I know will lead to a predictable outcome in terms of effort and function (except for the optional XML stuff)
Hence your indecision. :-)
VB looked great at the beginning until the projects where about 80% done, then the pain started and the DLL coding in C. I am concerned history could repeat itself if I choose .Net. My primary objective is the functionality. Effort is a concern. The XML parsing is optional.
.Net is an entirely different beast from VB. Most of the things you wouldn't be able to do in VB, or at least do them easily, are supported by .Net. For instance, Windows Services are a snap to build in .Net. Socket programming is also supported, but there are very few reasons to do it yourself, as you've got loads of communication APIs with .Net. You've got web-services, .Net Remoting, MSMQ management, and more recently WCF. Proper multithreading is supported by .Net, unlike the idiotic apartment model in VB. In case you really need to go low level, you can also actually use pointers in C#, inside of unsafe code blocks, even though I would never advise to do so.
If you really need to do things in C, then integrating is also relatively easy. You can create COM objects and use interop to work with them from .Net. You can also interact directly with plain ol' dlls using DllImport. Using www.pinvoke.net makes it easier.
When I developed in VB, sometimes I also had to go back to C++ to do stuff that I wasn't able of doing in VB. Since I began programming in .Net, the only extremely rare scenarios I would need to go back to C++ were when I needed to use legacy COM components that used types I was having a hard time to marshal via interop. I wouldn't worry about history repeating itself.
If you're using COM, you may be interested in using C# 4.0 instead of earlier versions - the downside being that it's only in beta. But basically it makes COM stuff somewhat less ugly for various reasons.
I'd expect there to be plenty of good C libraries for XML parsing by now. I would expect the main benefit to actually be the knowledge gained. I doubt that you'll actually produce the code faster for this project, but the next one may well be a lot quicker.
How much do you care about learning new stuff?
It sounds like an ideal project for learning C# & .NET.
You know most of what you need to do so you can use that to gain a base level of understanding of C# & .NET which you can then apply to the stuff you need to learn.
As Rune says though, a key driver could be the timescales. If this is something you need in a hurry then coding it in C & using win32 directly might be the answer.
Sorry I couldn't be more definite.
I think you should use C#. With your experience the learning curve won't be too steep. The code will ultimately be cleaner (and less of it) than you probably could with C/Win32.
There is probably going to be no problem using your existing C-library with the [DllImport] attribute.
It depends. :-) It depends on whether you want to do this quickly or if you want to learn something new. It depends on whether you will be the only maintainer of the code or if others will maintain it in the future. It depends on how complex your xml handling will be and on how complex the COM automation is.
You will probably get a working application quicker if you do it in C than in C#. Both since you have much of the stuff needed already in place and since you know C well.
But this project sounds like a good match for C# and .Net. .Net has great support for XML and COM interop is easy but clumsy in C# (much better in the next version!). So if you are interested in learning C# and .Net this would be a good project to do so.
I would definitely do this in .Net and probably C# (but I am biased). Using .Net would probably result in code that is easier to read and maintain and most probably easier to write. So if you are interested in learning C# I would suggest you go for it!
Edit:
You worry about the size of the executable if you write it in .Net. I doubt that will be a problem, for most if not all of the libraries you will use for a project like this will already be installed on your computer. 1 Mb is rather large for a .Net executable, event for a big project.
a short notice on the installation. .NET is as default xcopy-able so you wouldn't need an installer for the exe to be usable. Mail it around (or with the next release of the .NET framework optionaly leave it on a network share)
You could look at building a hybrid system that uses C++/CLI and C#. C++/CLI provides a nice bridge between the two and lets you easily split different parts of the system between the managed and unmanaged worlds.
Not sure if the setup projects are included in the free versions of visual studio. But you could use clickonce (included with the framework) or WIX (open source XML based msi creation tool).
learning C# will all be about the .Net libraries and not actually about the language
No there are many things you need to learn about the language (delegates , events , generics ...) and also it is object oriented and it manages the memory by itself and yes no pointers :)
anyway C# and .NET are great all you need is some effort to get up to speed

Categories