1

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.

sangfroid
  • 3,733
  • 11
  • 38
  • 42
  • Any reason you aren't considering using JNI? – Jyro117 Feb 09 '12 at 22:25
  • Apologies -- not familiar with JNI – sangfroid Feb 09 '12 at 22:26
  • I have never actually used it myself, but I'm sure someone else can explain it in more detail. Essentially, it allows you to access native code outside of the JVM or have native code call your Java code. Take a quick google search, the actual name is Java Native Interface. – Jyro117 Feb 09 '12 at 22:29
  • http://home.pacifier.com/~mmead/jni/cs510ajp/index.html http://www.pacifier.com/~mmead/cs510jip/jni/ – Sergey Benner Feb 09 '12 at 22:29
  • JNI sounds like only part of the needed solution. A good answer would recommend a toolset, perhaps code generator, to facilitate it. – Keith Feb 09 '12 at 22:34

3 Answers3

2

I am currently using a package aptly named javacpp. I believe it is worth taking a look at

hatboyzero
  • 1,929
  • 1
  • 21
  • 44
Mr.Powers
  • 163
  • 7
1

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.

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
1

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.

Community
  • 1
  • 1
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187