I'm working with a project that was built in C++. Within this project are public classes that contain public methods that I would like to call from my Java code. What's the best way to make this happen? I imagine I'd want something that would compile the C++ code down to bytecode.
I've seen a couple tools that do something like this, but some of them have not been updated for a very long time, and others seem inappropriate for the task. Are any of these tools mature enough to be used for a professional-grade app? Although open-source is preferable, I'm equally willing to consider commercial tools.
I am currently using a package aptly named javacpp. I believe it is worth taking a look at
There's always the old standby, JNI, known for being slow and very hard to use.
JNA is something I've never used personally but "I've heard good things" and it looks like it might fit your bill.
An alternate and potentially better approach would be to restructure your C++ code as a service that listens on e.g. TCP or UNIX sockets. This would increase the portability, make it possible to connect to it from most languages, and is not Java-specific.
Bridging C++ to Java using JNI (Java Native Interface) is actually pretty easy. Downside is you need to compile the C++ part for the platforms you want the code to work with.
I've got an example of calling Java from C++ in this post Can C++ call Java code? but calling C++ from Java is quite similar.
Related
A quick question that may seem out of the ordinary. (in reverse)
Instead of calling native code from an interpreted language; is there a way to compile Java or Python code to a .dll/.so and call the code from C/C++?
I'm willing to accept even answers such as manually spawning the interpreter or JVM and force it to read the .class/.py files. (is this a good solution?)
Thank you.
gcj can compile most Java source to native code (linked with a libgcj shared library) instead of to JVM bytecode.
There are a number of Python projects that are similar, like shedskin, but none as mature or active.
Cython is similar, but not quite the same—it compiles modules written in a Python-like language into native C extension modules for CPython. But if you put that together with embedding Python in a C app, it gives you most of what you want. But you are still running a Python interpreter loop to tie all those compiled-to-C functions together.
You can also do the same thing with Java—embed the JVM into your app, use gcj to compile any parts you want to native code, while compiling other parts to bytecode, and using JNI to communicate between them.
And of course you can use Jython to embed your Python code into the JVM, which you can embed into your C program, and because you can use JNI directly from Jython any pair of the three languages can effectively talk to each other without going through the third.
The idea of spawning a JVM or a CPython interpreter as a subprocess, which I think you were suggesting in your question, also works just fine. However, the only interface you will have to it in that case will be the child process's stdin/stdout/stderr (or any pipes or sockets you create manually), which isn't as flexible as being able to call methods directly on objects, etc. (Then again, sometimes that extra indirection can be a good thing, forcing you to define a cleanly-separated API between your components.)
You can embed a Python interpreter in your C/C++ program.
http://docs.python.org/2/extending/embedding.html
With Java your probably want the Java Native Interface (which works in both directions).
http://en.wikipedia.org/wiki/Java_Native_Interface
You can also look into Lua, while not as widely used as a lot of other scripting languages, it was meant to be embedded easily into executables. It's relatively small and fast. Just another option. If you want to call other languages from your c/c++ look into SWIG.
I develop applications/programs in C/C++. I am more versed in these two languages and love being a C++ developer. I am wondering how to create a Java program that contains all my C++ code.
I mean, I would like to wrap all my C++ code (that is already developed) inside Java class. But clueless how to do it.
Please post your responses or methods/steps on integrating C++ inside Java.
(using JNI is the way, but I could not figure it out on www how to use it)
FYI, I use Eclipse IDE to develop.
How and what packages should I include in my project workspace?
Instead of JNI, or JNI with some assist from an automatic wrapper generator like SWIG, or even JNA, you might consider separating the C/C++ and Java into separate processes and using some form of IPC and/or Java's Process abstraction to call to a program written in C/C++. This approach abandons "wrapping," so in some sense it isn't an answer to this question, but please read on before down-voting. I believe that this is a reasonable answer to the broader issue in some cases.
The reason for such an approach is that when you call C/C++ directly from Java, the JVM is put at risk of any error in the native code. The risk depends somewhat on how much of the native code is yours and how much you link to third party code (and how much access you have to the source code of such third party code).
I've run into a situation where I had to call a C/C++ library from Java and the C/C++ library had bugs that caused the JVM to crash. I didn't have the third party source code, so I couldn't fix the bug(s) in the native code. The eventual solution was to call a separate C/C++ program, linked to the third party library. The Java application then made calls to many ephemeral native processes whenever it needed to call the C/C++ stuff.
If the native code has a problem, you might be able to recover/retry in Java. If the native code is wrapped and called from the JVM process, it could take down the entire JVM.
This approach has performance/resource consumption implications and may not be a good fit for your application, but it is worth considering in certain situations.
Having a separate application that exercises the functionality of the C/C++ code is potentially useful as a stand-alone utility and for testing. And having some clean command-line or IPC interface could ease future integrations with other languages.
As another alternative, you could get into native signal handling to mitigate the risks to the integrity of the JVM process if you like and stick with a wrapping solution.
If you want to call C++ from Java, you'll need to use JNI - Java Native Interface.
Be warned that you lose some of the benefits of the garbage collector, since it can't deal with your C++ objects, and your code won't be portable anymore.
Maybe you'd be better served by learning to write 100% Java and leaving C++ behind, but that's just a suggestion.
You can't "just wrap it", you have to write some C/C++ glue.
For starters, SWIG can do most of the works for you.
There are plenty of tutorials for doing exactly what you want to do. For example, check out: http://www.javamex.com/tutorials/jni/getting_started.shtml
There are also plenty of caveats of using JNI. I've recently started working with it (just for fun, really), and it tends to be a lot less fun than I had first anticipated.
First of all, you have to deal with cryptic code such as:
#include "test_Test.h"
JNIEXPORT jint JNICALL Java_test_Test_getDoubled(JNIEnv *env, jclass clz, jint n) {
return n * 2;
}
Second of all, it tends to downplay one of the primary reasons why you use Java in the first place: WORA (Write Once, Run Anywhere). As duffymo mentioned, there can also be issues with the garbage collector, but I think that in recent years, the JVM has gotten pretty smart about JNI integration.
With that said, to port all of your C++ code to JNI, you'd need to refactor your interfaces (and maybe even do some internal gymnastics). It's not impossible, but it's really not recommended. The ideal solution is just re-writing your code in Java.
With that said, you could also "convert" your code from C/C++ into Java programatically, and there are multitudes of such utilities. But, of course, machines are dumber than people and they are also bound to make mistakes, depending how complex your class is.
I would avoid JNI because it's tedious to write, verbose, and just an altogether pain. Instead I'd use JNA library which makes writing native integration so simple.
https://github.com/twall/jna/
Good luck.
You can write C++ code through JNI but there isn't a direct mapping from C++ classes to Java classes.
I've used JNI to fix problems found in the android SDK (specifically, an incredibly slow FloatBuffer.put implementation) and I may end up using it for some performance critical areas. My advice would be to be use it sparingly and in a duck in, do the performance critical stuff and leave, without doing any memory allocation if you can help it. Also, don't forget to measure your code to see if it really is faster.
Out of interest, what platform are you developing for? The only platform where it would make sense to wrap a lot of C++ code in a light java layer would be Android - on other platforms, just compile in C++ and have done with it.
JNI module is not a Java classes. It's C. Using JNI incur many restrictions and some Java environment doesn't support JNI well.
There is no supported way of "wrap my C++ code inside Java class" (EDIT: I mean, without JNI noway but JNI is problematic.)
You could investigate custom C++ compiler emit Java byte codes, but nobody (include me) will recommend this approach.
BridJ was designed on purpose for that (and it's supported by JNAerator, which will parse your C/C++ headers and spit out the Java bindings for you).
It is a recent alternative to JNA, with support for C++.
Is it possible for a developer to use Scala without knowing Java?
Is it possible for a developer to use Clojure without knowing Java?
Note: For example I am a C# developer and I use .NET without knowing any VB (Of-course WF 4.0 uses VB for statements, so I refuse any projects involving WF 4.0 :) ).
Summary I: Thanks to all for your answers. Now I can tell one can use these languages without knowing Java (The Language). Now I've got another question: How can one start with Java (JVM) ecosystem? What are beginner, intermediate and advanced knowledge-bases (bags!)? To be honest Java ecosystem was always a bit confusing to me, so it would be very helpful to provide some "reference references" and "defacto tutorials" for learning (curve!) JVM.
(OK! I will post it as another question!)
Scala, and Clojure even more so, are totally different languages from Java. The only thing they have in common is that they run on the Java virtual machine. You do not need to know the Java programming language to program in Scala or Clojure. It would be useful, however, to know something about the Java ecosystem (the Java virtual machine and runtime environment).
Sure you can. You'll lack the knowledge of the standard library at first, but that's not a big problem when you're starting with a new languages anyway. Clojure & Scala, however, put a heavy emphasis on the Java interop and do not try to hide the raw Java stuff, so you'd probably have to learn more about Java(not the language - the Java Platform) at some point to make maximum use of the language and the underlying platform.
Speaking from the perspective of knowing Java and Clojure (but not Scala), you can use Clojure just fine without knowing Java. You have access to the core language, which is fully-featured, and libraries (e.g. clojure-contrib).
However, one of the big benefits of using Clojure (versus other lisps) is access to the Java ecosystem - libraries, debuggers, JVM, etc.
So, yes you can use Clojure effectively and I wouldn't let a lack of Java knowledge hinder you, but you'll add to your bag of tricks if you eventually start to learn enough Java to take advantage.
Well, Clojure has been ported to the CLR. Probably easier thant the whole jump to the JVM since you are a .NET developer. :)
http://github.com/richhickey/clojure-clr
yes, thats me!
Has not been much of a problem for me except for when I needed a stupid simple swing gui. thats when I had to go back and review java.
Scala is totally different language than java. So yes, you can of course use scala without knowing java ( but of course you have to learn scala first). Even though, knowing java (or any OO language) + some functional language makes it easier to understand scala.
I have an application written in C++ (makes heavy use of templates) that I need to take to the Java ME platform.
I have two questions:
Are there any good tools to convert C++ code to Java - do some basic stuff so I have a platform to start with. I found this - http://tangiblesoftwaresolutions.com/Product_Details/CPlusPlus_to_Java_Converter_Details.html. It would at least eliminate the need for simple but time-consuming stuff like moving classes to different files, namespaces to packages, etc. Has anyone tried it? Or knows of any better ones?
The bigger problem is how to deal with templates - the code makes very heavy use of them. Any suggestions on how to go about this? Are there any tools to expand templates for instance so I have a rudimentary base and then I could work on writing the modules in Java?
Any help would be appreciated.
For all of Sun's marketing, Java is not simply a better C++, and in fact does not support many of the idioms and paradigms C++ supports. This makes automated translation difficult. How should you automatically turn a multi-inheritance hierarchy into Java's single inheritance hierarchy? (Note, I am not saying that a multi-inheritance hierarchy is a good thing, only that it is explicitly allowed in C++). More fundamentally, how would you represent a pointer-to-member function in Java? Or handle the differences between Java and C++ overload resolution?
Java added generics a few years ago, but purposely made them less powerful than C++ templates. Regardless of whether that was a good idea, it limits what automated translation can do with heavily templatized code.
Aside from using some research compiler that can turn C++ into Java bytecode, I'm afraid you may be stuck doing the translation by hand.
Can you use JNI and call the old C++ code from the new Java code?
I think for your case a very simple tool would be possible and perhaps worthwhile. Might be a fun weekend-job, though! A friend of mine once did a port from C++ to Java and he just made a list of regular expression substitutions. Like, he had all occurrences of -> replaced by a dot. And so forth. This was some years ago, however, so I don't really feel like asking him.
So, you could do the same, collect some easy substitutions and perhaps publish them somewhere on github?
Generics is the Java feature that corresponds to C++ templates and they are not supported in J2ME. You can use them with the aid of a framework, which probably uses pre-processing to do the trick. (Actually Generics in Java is a compiler feature - the JVM knows nothing about them.)
Anyway, it will be difficult if not impossible to automatically port even a small portion of your code form C++ to Java Standard Edition - things are much worse with J2ME. There are many and important differences between Java Generics and C++ templates.
I don't think it's going to be possible, esp. if your original code is heavily templatized - J2ME doesn't support generics, AFAIK.
Unfortunately, it seems like this will require a lot of manual work to go through the original code and rewrite it (I'm assuming your target platform doesn't support JNI)
I have to integrate a large Java library in a quite large C++ application. A solution is to use JNI but this requires to hand code all the classes. Python has, for example, a wonderful solution with JPype (http://jpype.sourceforge.net/) that automatizes the process (although the same solution cannot be applied to C++ due to C++ and Python different natures).
Thanks,
Das
SWIG is a tool that lets you auto-generate bindings from one language to another. It supports C++ and Java and a dozen other languages.
Seems that my question was not clear enough. Maybe the confusion comes from JNI that allows the access in booth directions ...
What I want to do is to access a Java library FROM C++. That is, someone give me a JAR file that contains a collection od JAVA compiled classes and I must write code in C++ to access it (as I want to integrate the functionality of that Java library into a C++ application).
Hope that this clarifies the direction of access :)
Thanks,
Das
Not sure if this commercial tool makes life any easier, but you might wanna explore -- http://www.teamdev.com/jniwrapper/index.jsf
JNA is not quite what you're looking for, but it does make your life a lot easier. It doesn't require any boilerplate/generated code - you just write an interface for the methods you want to call.
Certainly, there is every reason to use JNA instead of JNI.
I have two suggestions which may or may not work for you:
First, you could try something very simple. Run the Java code in a separate process, and communicate with it with pipes or sockets. This is fairly easy to do, and doesn't require any crazy libraries. The downside is that the communication is somewhat limited (just some simple pipes), you'll need to write your own wrapper around it to send data across
Secondly, what exactly is this library? Perhaps we can suggest alternatives that are not written in Java, that would be much easier to use in your C++ application?