0

Background:

  1. I am new to the JNI world, and not an experienced C programmer.
  2. I want to write an JNI for connecting a Java toolkit and a library in C (not just for speed, but for good functionality as well)

I've seen some code using C++ for doing such work. And since managing resources in C requires more explicit manual control, I'd like to give C++ a try.

Question: Would the mixing of C++ with C here cause problems that I could not see?

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
CloudyTrees
  • 111
  • 2
  • Managing resources in C++ is also a manual operation. The only difference is that there are some facilities in C++ that ease this process, like RAII and smart pointers. – Robert Harvey Aug 01 '16 at 21:48
  • @RobertHarvey, yes, that's what I meant, in particular, the destructor. Sorry for the confusion. – CloudyTrees Aug 02 '16 at 00:47

2 Answers2

1

No, it wouldn't.

I have an Android app whose core functionality is in 8,000 lines of C++ (shared with other platforms) with a Java UI wrapped round it using JNI and there have been no problems at all.

So if you prefer C++ to C, use it.

1

The C++ wrapper of JNI is easy to use, and its object orientation is well designed. I personally find it makes the relationship between the JNI objects somewhat more visible and understandable than in the C interface (see examples here) .

As you pointed out, if you're doing heavy C++ work to call some Java functionality, you could elaborate a little more the design and use constructors/destructors to automate some tasks that you would have to manually code in C.

However if you're doing the things the other way round, calling native C/C++ functions from Java, C++ won't bring you a big benefit: this calling interface is really designed for calling C functions (or static C++ functions with exposed as "C"). So if you want to use C++ classes, you have to organise the link between the static world and the objects that you create on C++ side.

Both can of course perfectly interoperate.

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
Christophe
  • 74,672
  • 10
  • 115
  • 187
  • Thanks @Christophe. I've tried one JNI project before, and the input was some large number of strings (technically a little bit more than strings), so to make things a little more efficient by minimizing interfacing C-Java, I allocated "enough" space in C at the beginning and had to manage the intermediate resources "painfully" until things are returned back to Java. This is why I want to try C++. – CloudyTrees Aug 02 '16 at 01:01