Is there any tool/software available that does porting from C++ to Java
Hi we have a project/product which 开发者_JAVA百科is written in C++. Now we are planning to convert it into Java for getting benefit of Java.
Is there any tool available for doing this porting? What is the best way to start?
I've seen some attempts at automated code conversion, and while it can technically "work", the resulting code is often completely unmaintainable. The major problems are:
- Some concepts don't translate cleanly, and require some extremely messy (and often slow!) interpretation or wrappers to get the same results.
- Good Java code is structured and styled very differently from good C/C++ code. If you auto-translate the code, you'll end up structure and style that is very unidiomatic in the target language, and subsequently very hard to understand/maintain.
- Some code can't be translated at all (e.g. some of the more arcane memory management code in C/C++ simply can't be done in the Java memory model). This will break any auto-translation, and need to be rewritten completely.
I'd therefore suggest piecewise conversion, rather than trying to convert the whole product using a tool. For example, you might adopt the following approach
- Start by creating a Java application (or web app) as a "wrapper" for the C/C++ code. Can be just a simple interface at this point.
- Figure out a how to do Java <-> calls (hint: JNI)
- Use JNI to call the C/C++ code as a black box "engine".
- Write a lot of JUnit tests that check you are getting the results you expect. This is not only good practice generally, but will help you massively in terms of avoiding bugs when you make future conversion steps.
- Over time, convert components of C/C++ into Java. Replace each JNI call to these components with a call to some Java code, which may make lower-level JNI calls to the remaining C/C++ code base as needed
- Use each translation step as an opportunity to refactor your code. Define clear service-based interfaces, reduce duplication, make things immutable, etc.
Swig doesn't port from C++ to java per-se, but it does automatically generate wrappers for existing type hierarchies so you can call (and extend) C++ code in Java. Depending on what exactly you're aiming to achieve this might be useful and vastly simpler, for example it would allow you to access legacy code from a new Java code base.
You want to convert it into Java, then you loose portability and performance, but that's your decision ;)
However I don't think it's possible, because of the fundamental differences between the two languages. For example in C++ it's possible to allocate objects on either the heap or stack, where in Java you can only put "primitive types" such as int and float on the stack; for Objects the heap is used which is managed by the garbage collector. Also Java ships with a much larger standard library so the STL code (if STL is used) would have to be ported to that too..
精彩评论