Progress-servis55.ru

Новости из мира ПК
9 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Конвертер c в java

Конвертер c в java

GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Clone with HTTPS

Use Git or checkout with SVN using the web URL.

Downloading

Want to be notified of new releases in danfickle/cpp-to-java-source-converter ?

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio

Latest commit

Files

Permalink

TypeNameLatest commit messageCommit time
Failed to load latest commit information.
lib
src/ mainRemove a wrong/unused import. Add .settings to .gitignore.Dec 20, 2014
testsAdded expression ptr — ptr.Jan 29, 2014
.gitignoreRemove a wrong/unused import. Add .settings to .gitignore.Dec 20, 2014
LICENSE.txtMavenized project. Added copy of Apache License.Dec 20, 2014
README.mdMavenized project. Added copy of Apache License.Dec 20, 2014
pom.xmlMavenized project. Added copy of Apache License.Dec 20, 2014
working-notes.txt

C++ to Java Translator

This project aims to convert C++ code to high level Java source code. Where that is not possible, a TODO should appear in the generated source code.

The project is about three quarters of the way to an initial release. The below items will not be handled by the initial release:

  • goto statement
  • untyped malloc
  • template code generation (generics to be used instead).
  • C++/C std lib
  • order of operation differences
  • platform dependent/undefined behavior
  • unions
  • dynamic cast and other RTTI features
  • multiple inheritance
  • C++11 features
  • overloaded operator new and operator delete memory management

Everything else should work with the initial release.

The following lines give an indication of what generated code using pointers looks like.

This fork will build with Maven. Eclipse CDT is not in Maven central, or any repository I could find, but for your convenience, private copies of certain JARS are shipped in the lib/ directory:

  • org.eclipse.cdt.core_5.4.1.201209170703.jar
  • org.eclipse.equinox.common_3.6.100.v20120522-1841.jar
  • com.ibm.icu_50.1.1.v201304230130.jar (I needed it at run-time once to fix a logging error)

Please note these are from a separate project with separate licenses.

Historical required JARs:

These are the JAR files I use to get this code to run. They are from Eclipse Juno (4.2.x) and CDT 8.1.1 for Eclipse Juno. Additionally, jOOR is required by the runtime template handling code.

This project is licensed under the Apache license. The CDT walking code is based loosely on code I found (and lost the url) on the web (also licensed under the Apache license).

This is an incomplete and fluid list of items that need doing before the initial release.

  • General
    • Lots more assertions
    • Destructor calls on static duration objects
    • Cast operators other than C style cast should not resolve overloaded operator cast
    • Basic type classes other than MInteger
    • Global variables
    • Templates
    • Should be able to take the address of an enumerator
    • Putting in comments/defines from original
    • A lot of work on multi dimension arrays.
    • cleanup cpptojavatype method.
    • function pointers.
    • typed malloc.
    • testing cleanup.
    • making logger useful.
    • relacing deprecated methods.
    • make lists.
    • correct names (camel case, capitalized classes etc.)
    • Varargs.
    • Bracketed expressions
    • Special case this pointer and void pointer.
    • exact bit position for bitfield.
  • First pass
    • Recursively evaluate templates and generate expanded cpp code.
    • Generate implicit special methods and output cpp code.
    • Record if a basic variable(int, bool, etc) has its address taken so we can skip objectifying it if it does not.

Делает Java для инструмента c конвертером++/существует? [закрытый]

Я всегда спрашивал себя, можно ли сделать конвертер Java в C++.

может быть, инструмент, который преобразует синтаксис Java в синтаксис c++?

Я знаю, что языки отличаются, но простые вещи, такие как петли, где семантика соответствует 1 к 1.

есть ли такой инструмент? Или его можно сделать?

10 ответов

можно сделать все, что угодно, учитывая достаточно времени, денег и ресурсов. Это практично? За пределами тривиальных примеров не очень. Или, скорее, это зависит от того, что составляет приемлемую частоту ошибок.

реальная проблема заключается в том, что фразеологизмы отличаются в Java и C++. Например, Java для C# было бы намного проще (потому что идиомы гораздо более похожи). Самым большим, конечно, является то, что C++ имеет деструкторы и управляемую вручную память. Java использует блоки finally для этого поведения и сбора мусора.

также Java имеет общий супертип объекта. C++ не поддерживает.

дженерики к шаблонам были бы почти невозможны, я бы предположил.

на Firefox HTML5 parser написан на Java и преобразован в C++. Но я думаю, что конвертер, используемый там, вполне специфичен для этого проекта. Интересно, что получившийся парсер C++ оказался быстрее, чем старый парсер, написанный на C++.

Я также пишу конвертер как часть базе Н2, в разделе src/tools/org/h2 / java. Идея заключается в том, чтобы разрешить преобразование подмножества базы данных H2 в C++, поэтому это также не является общей целью переводчик.

и есть проект с открытым исходным кодом идентификации j2c.

Итак, есть способы конвертировать Java в C++. Но не ожидайте, что переводчик поддерживает все функции, и не ожидайте, что результирующий код будет быстрее, чем хорошая Java JVM.

возможно, без вопросов, но это будет не так просто. Это будет компилятор Java, который генерирует C++.

Если вы хотите сделать это с нуля, это будет очень сложно, вы должны сделать всю работу javac и JVM для вас (например, сбор мусора).

кстати. У Google есть компилятор Java для JavaScript (входит в GWT)

странно, как есть конвертеры c++ для java, но только 1 Java для конвертера c++.

Как сказано, было бы трудно преобразовать Java в C++, но у нас может быть приложение или инструмент, который генерирует код в Java и equivalnet c++.

Я знаю одно приложение, которое генерирует код в C++ / Java / C#, учитывая модель, которая имеет свой собственный способ ее определения.

этот инструмент принадлежит CA и имя CA Plex. Поиск на www.ca.com

есть программы, которые утверждают, что они могут это сделать, но ни один из них не приобрел достаточной популярности, чтобы часто упоминать, поэтому мы оставим их в «попытках». Создание конвертера потребует много ИИ, встроенного в вашу программу. Сложность увеличивается в десять раз, когда swing участвует, потому что GTK/wxWidgets/Qt/win32 API все сильно отличаются от swing. Но это возможно. Не то, чтобы качество кода будет отличным, и нет гарантий, что ваша программа не рухнет из-за отдельной памяти методы обработки, но это возможно.

основная проблема заключается в том, что java-это язык, который написан и предназначен для общения с виртуальной машиной. Я предполагаю, что это будет возможно, но все, что вам останется-это очень плохо оптимизированное приложение с переводом слой делает то, что ВМ уже не. Я имею в виду, конечно, это возможно, это все равно не было бы решением для чего-либо, что я мог бы придумать. Если вы хотите сделать свое вялое java-приложение родным, возможно, ваше мышление слишком сложно, просто используйте приложение, такое как JET, его на самом деле довольно хорошо, и даст вам преимущества, которые принесет родное приложение. Конечно, если VM уже делает то, что приложение просит его сделать так же хорошо, как и собственный код(это происходит.. иногда: P) это может ничего не изменить.

Java для c#, tho, звучит более разумно, поскольку оба языка написаны аналогично, разговаривая с фреймворком как таковым, но это все равно оставит код очень неоптимизированным, поскольку код, написанный с нуля для конкретной фреймворка, не может быть превзойден.

зависит от области, где будет использоваться код, с точки зрения обучения, возможно, это может быть интересно.

Я только что нашел это через google, поскольку я помнил, что видел один в Univeristy, который создал код на основе uml.

Java в C будет проще. Помните, что вам нужно преобразовать язык, Если вы это сделаете, необходимые библиотеки могут быть преобразованы вашим новым компилятором. Другими словами, Swing и AWT не должны быть большой проблемой.

Я бы начал с хорошего взгляда на собственный интерфейс Java (JNI). JNI является частью java, которая позволяет использовать его с C и c++. Причина, по которой я бы начал здесь, заключается в том, что становится довольно очевидным, как части Java могут быть реализованы в C. Как только я понял основные структуры, например, как объекты Java могут быть сопоставлены с структурами C (struct) и как почти все в Java является объектом, включая массивы, я мог бы заглянуть в открытый исходный код JDK.

фактический конвертер должен был бы преобразовать все импортированные библиотеки Java (и их импортированные библиотеки и так далее. ) что означает, что вам понадобится исходный код для всего. Это преобразование не маленькая задача, так как библиотеки Java большие.

в процесс займет много времени, но ИИ не потребуется. Однако я не вижу причин для такого преобразования. Он теряет переносимость Java и не будет получать эффективность C (за исключением того, что он будет скомпилирован в собственный код, но было бы лучше скомпилировать машинный код непосредственно из Java).

Looking for the Code Converter which converts C# to Java

Can anybody help me by suggesting the name of an converter which converts C# code to Java code. Actually, I have a tool which is written in C# code and I am trying to modify it. As I have no idea about C# and .NET framework, it seems difficult to me to convert the large code by my own. I found from some web information that there exist some tools which can convert C# to Java (may not be properly, however they can). Can anybody help me by suggesting some name of those tools.

Создан 11 авг. 11 2011-08-11 16:58:09 Arpssss

IMO such tools are only useful if you then have enough knowledge of both source and target language to fix the mess it makes. – Marc Gravell 11 авг. 11 2011-08-11 17:00:35

I have some knowledge of Java and about the functionality of above mentioned tool. However, no knowledge of C#. Will those tools help me ? What do you think ? – Arpssss 11 авг. 11 2011-08-11 17:04:37

@Arpssss — if you don’t understand the C# code then you probably don’t know, if the translated Java does the same — unless you have test cases for both c# and java. – Andreas_D 11 авг. 11 2011-08-11 17:07:36

Just to cite a few things that won’t translate well. structs, nullables, iterator-blocks, anon-methods, lambdas (differed capture rules), string-equality, LINQ, most of the BCL, dynamic, operators, delegates, events, generics-without-type-erasure. – Marc Gravell 11 авг. 11 2011-08-11 17:15:33

possible duplicate of [is there an effective tool to convert c# to java?](http://stackoverflow.com/questions/78811/is-there-an-effective-tool-to-convert-c-to-java) – user195488 11 авг. 11 2011-08-11 17:48:41

Christopher, I am agree with your answer.However, I started to learn C# thus I can convert by my own. But, I think Marc is right on that «they actually are pretty different» . I also feel the gap while studying c# (it became more tough because the complete tool is on c#).That’s why I am searching for a converter . – Arpssss 11 авг. 11 2011-08-11 17:53:46

I found by searching the web that (http://www.kevingao.net/csharp-java-conversion) this gives reasonable conversion (however, I have not yet tested with my code). I know it is impossible to convert properly because of the syntactic and semantic gap of them. Actually I thought like that, convert the C# code by using a commercial converter and then modify it by your own . – Arpssss 11 авг. 11 2011-08-11 17:55:05

All, let’s just provide him a converter, not a lecture. – user195488 11 авг. 11 2011-08-11 17:55:41

Code Monkey, thanks for making my question more clearer. – Arpssss 11 авг. 11 2011-08-11 18:51:00

2 ответа

Disclaimer: No tool is perfect.

However, if you still want to try then there are these converters available:

Not a converter but a bridge between .NET and the JVM:

Создан 11 авг. 11 2011-08-11 17:53:12 Anonymous

I am searching for a tool which converts C# code to Java code. Is these tools can convert (I am not caring about perfectness)? – Arpssss 11 авг. 11 2011-08-11 18:01:13

@Arpssss: Yes, only exception is JCLA which is the opposite: Java to C#. – user195488 11 авг. 11 2011-08-11 18:02:25

Thanks Code Monkey.. – Arpssss 11 авг. 11 2011-08-11 18:03:41

The Grasshopper link does not work. The dev.mainsoft.com site throws an error and mainsoft.com redirects to http://harmon.ie/. – Trisped 17 апр. 13 2013-04-17 19:16:19

The CSharpJavaMerger page looks like it has been hacked (title says «Nothing found for Csharp-java-conversion» but page is selling HYDROXYCITRIC ACID). Also, there is not a link on http://www.kevingao.net/ to the page. – Trisped 17 апр. 13 2013-04-17 19:17:14

@Trisped There’s nothing wrong with the [CSharpJavaMerger](http://csharpjavamerger.org/get-source-code.html) link. It points to the correct page now. – Anderson Green 22 дек. 15 2015-12-22 19:19:41

@AndersonGreen Yeah, looks like user195488 fixed it right after I put up the comment. – Trisped 22 дек. 15 2015-12-22 20:55:23

You are better off doing it by hand. I’ve used code conversion software before, and it just mucks everything up. Sure, it corrects a few syntax differences, but largely what you’ll get is just a mess of code that doesn’t compile right away anyway.

With a converter you’ll have to do a lot of corrections anyway. Why not take the small amount of extra time it will take to convert it by hand and end up with better code?

Even if you don’t know C#, it will be better to learn it and do the conversion by hand, as I said before you will have to do it anyway. C# and Java are not too different syntactically, but as @Marc pointed out above, there are certainly gaps in the language. Simple C# is easily translated to Java, of course having to use the Java BCL instead of the .NET, which certainly have their differences. As you get into more complicated C#, there are things that have no direct equivalent.

Keep in mind, that conversion projects can be extremely time-consuming and are extremely effective at swallowing money in a business environment.

A google search will yield you some commercial options, but I’m not going to post them here, simply because I’m against that sort of thing. There are some things you just can’t automatically translate.

I added a brief list of things that will make conversion tricky (comment on the question) — it makes me think that the «not too different» is generous — they actually are pretty different – Marc Gravell 11 авг. 11 2011-08-11 17:19:51

I *was* being generous, I think because I was speaking from my experience of going from Java to C#, which is admittedly easier, though still not without its own share of difficulties. I’ve updated the answer to reflect your insight. Thanks. – Christopher Currens 11 авг. 11 2011-08-11 17:24:28

Microsoft provides a tool to go from Java to C# so if Microsoft supports it, I don’t see why you can’t do it. Understandably that you want to make sure the code still works when you convert it. – user195488 11 авг. 11 2011-08-11 18:01:41

He’s asking for code that goes from C# to Java, not the other way around. There’s a large difference, as it is somewhat easier to convert Java to C#. I’m not saying he can’t use a tool, but I can say *from experience* he is better off writing it by hand. If the project is so large that he can’t do it by hand quickly, try a tool, but he will have to make so many changes it may not be worth it. – Christopher Currens 11 авг. 11 2011-08-11 18:04:39

@Chris: I know. I really don’t think he wanted a lecture, just a tool. You ask a question, get an answer. I’m sure if he wanted an opinion on tools then this all would be appropriate but everyone slammed him which is not the right way to treat someone asking a simple question for a list of converters. That’s as simple as this question really was and everyone just blew up on him. I flagged all the above comments as not constructive. – user195488 11 авг. 11 2011-08-11 18:07:46

I think everyone was trying to save him the headache. I guess some people have to learn the hard way. – Christopher Currens 11 авг. 11 2011-08-11 18:09:54

Christopher, I understood what you are talking about. I have started to learn C# thus I can convert by my own (I know this is the best soln.). But the problem is that as Marc says » they actually are pretty different» and I feel it also while learning C#. Now as my code is too large, I thought like that, first convert it by any commercial tool and then fix the bugs, performance issues. What your experience says, is it a bad idea ? – Arpssss 11 авг. 11 2011-08-11 18:15:09

@Arpssss, There’s not an easy answer to that question. If you need the code quickly, it’s a fine idea, but do not go into it thinking the tool will make it easy for you. Regarding the differences Marc pointed out, the tool will not know what to do with those pieces of code, leaving them unconverted. You will have to convert those things that don’t have a direct translation by hand anyway. At the very least, the tool will convert the syntax and some common calls to the base libraries. However, it will not account for the differences between the two languages «best practices». – Christopher Currens 11 авг. 11 2011-08-11 18:22:59

Thanks Christopher, I think I got your point. – Arpssss 11 авг. 11 2011-08-11 18:37:40

You’ve clearly had one or more unsatisfactory experiences with one or more tools at some time in the past, converting from some language to another. Describing those experiences, naming the tools and the times and languages, and quantifying even a little bit what kind of code you fed in, and the amount and kind of deficiencies you found in the translated code — would make this a better answer for SO. – Spike0xff 23 сен. 15 2015-09-23 20:22:18

голоса
Рейтинг статьи
Читать еще:  Как восстановить документ эксель если не сохранил
Ссылка на основную публикацию
Adblock
detector