-6

I have found Java to be an excellent high level language but it lacks some of the speed and flexibility of its founding language C.

Seeing the Android OS was written in C and Java it seems likely that these two languages compliment each other well.

How does one import C code into a Java program?

PS. Bonus points if you know how to do this on the Android OS.

2 Answers2

1

For Android, the tool to use is the Native Development Kit. You can read about it (and get it) here. Note that they make the point:

you should understand that the NDK will not benefit most apps.

(Emphasis in the original.)

As @jdphenix points out in a comment, you need to be familiar with the Java Native Interface spec to integrate C/C++ code with Java. The NDK is a tool to support using JNI with Android apps.

EDIT (in response to comment): Using two languages because you need to use one (Java in the case of Android) and you like the other (C/C++) strikes me as counterproductive unless you have strong performance reasons to do so. As the docs for the NDK say:

[U]sing native code on Android generally does not result in a noticable (sic) performance improvement, but it always increases your app complexity. In general, you should only use the NDK if it is essential to your app—never because you simply prefer to program in C/C++.

Typical good candidates for the NDK are CPU-intensive workloads such as game engines, signal processing, physics simulation, and so on.

In addition, using two languages will make maintenance of your app much harder. Not only is JNI a difficult technology, the app will require maintaining skills in two languages. If you do need to use the NDK for performance reasons, I would strive to limit it to the bare minimum. Most of the Java framework is quite efficient, particularly with the Dalvik JIT compiler appearing on many devices.

Incidentally, if you are interested in Android game development in particular, you might also want to check out the Google Play Games C++ SDK. It's a companion to the NDK.

P.S. As of Android 4.4, there is an option to replace the Dalvik runtime with a new Android Runtime (ART). (Read about it here.) This compiles your app's bytecode into native code at the time the app is installed. The result is that much of the performance benefit of using JNI disappears when ART is enabled. I expect that future versions of Android will default to ART once Google has some confidence from testing it "in the wild." Just another reason against using JNI in your apps unless you really need to.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

The native keyword in Java can use code written in another language, using the Java Native Interface. Read more here:

https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

jackarms
  • 1,343
  • 7
  • 14