Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of the JNI?

I'm new to Java, and was told to use the Java Native Interface to run some code I wrote in C.

Now, this might be a stupid question, but what's the point of the JNI ? Can't I simply execute my process from a Java UI program and get its stdout to parse ?

Also, I've read that the use of JNI might cause security issues. Do these issues directly depend on the quality of the invoked code ? Or is this something deeper ?

Thanks.

like image 975
gqq Avatar asked May 31 '12 08:05

gqq


People also ask

Why do we need JNI?

JNI provides functions for accessing the contents of array objects. While arrays of objects must be accessed one entry at a time, arrays of primitives can be read and written directly as if they were declared in C.

Which one is a advantage of JNI?

Advantages of JNI in JavaIntegrates other Language Codes with Java: The sole purpose of Java Native Interface is to combine the code written in Java with code written in other languages like C & C++, which is mainly to bring additional functionality to the application.

Is JNI faster than Java?

When talking about JNI, there are two directions: java calling C++, and C++ calling java. Java calling C++ (or C) via the "native" keyword is very fast, around 50 clock cycles. However, C++ calling Java is somewhat slow.


1 Answers

what's the point of the JNI ?

It enables you to mix C and Java code within the same process.

Can't I simply execute my process from a Java UI program and get its stdout to parse ?

A lot of things that can be achieved by using JNI can also be achieved by using inter-process communication (IPC). However, you'd have to ship all the input data to the other process, and then ship all the results back. This can be pretty expensive, which makes IPC impractical for many situations where JNI can be used (e.g. wrapping existing C libraries).

Also, I've read that the use of JNI might cause security issues. Do these issues directly depend on the quality of the invoked code ? Or is this something deeper ?

The point here is that the JVM does a lot of work to ensure that whatever Java code is thrown at it, things like buffer overruns, stack smashing attacks etc can't occur. For example, it performs bounds checking on all array accesses (which C doesn't).

On the other hand, JNI code is a black box to the JVM. If there's a problem with the C code (e.g. a buffer overrun), all bets are off.

like image 106
NPE Avatar answered Sep 30 '22 19:09

NPE